how to do a button click in Xamarin Forms Android custom info window - google-maps

In my Xamarin Forms Android project I am showing a Map using CustomMapRenderer. I am popping up a Info Window in Map screen and this info window has button name called "Call". I need to do a "OnCLick" button click operation for this button. I have googled it, but unfortunately I didn't come across any solutions. at last I have started to work on converting the Android Native code -Java into Xamarin Forms Android - c#, for this conversion I have been using this answers Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps) . This converted code shows A field initializer cannot reference the non static field, method or property OnInfoWindowElemTouchListener.onClickConfirmed(view, marker) this Error inside Java.Lang.Runnable please help me to resolve the problem.
OnInfoWindowElemTouchListener.cs
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Gms.Maps.Model;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Views;
using Android.Views.Accessibility;
using Java.Lang;
namespace Hotel.Droid
{
public abstract class OnInfoWindowElemTouchListener : Java.Lang.Object
, View.IOnTouchListener
{
private View view;
private Drawable bgDrawableNormal;
private Drawable bgDrawablePressed;
private Handler handler = new Handler();
private Marker marker;
private static bool endPressStatus = false;
private bool pressed = false;
public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed)
{
this.view = this.view;
this.bgDrawableNormal = this.bgDrawableNormal;
this.bgDrawablePressed = this.bgDrawablePressed;
}
public OnInfoWindowElemTouchListener()
{
}
public void setMarker(Marker marker)
{
this.marker = this.marker;
}
public bool OnTouch(View vv, MotionEvent e)
{
if (0 <= e.GetX() && e.GetX() <= vv.Width && 0 <= e.GetY() && e.GetY() <= vv.Height)
{
switch (e.ActionMasked)
{
case MotionEventActions.Down:
startPress();
break;
// We need to delay releasing of the view a little so it shows the
// pressed state on the screen
case MotionEventActions.Up:
//handler.PostDelayed(ConfirmClickRunnable, 150);
Task.Factory.StartNew(() => onClickConfirmed(view, marker));
Task.Delay(150);
break;
case MotionEventActions.Cancel:
endPress();
break;
default:
break;
}
}
else {
// If the touch goes outside of the view's area
// (like when moving finger out of the pressed button)
// just release the press
endPress();
}
return false;
}
private void startPress()
{
if (!pressed)
{
pressed = true;
//handler.RemoveCallbacks(ConfirmClickRunnable);
view.SetBackgroundDrawable(bgDrawablePressed);
if ((marker != null))
{
marker.ShowInfoWindow();
}
}
}
public bool endPress()
{
if (pressed)
{
this.pressed = false;
handler.RemoveCallbacks(ConfirmClickRunnable);
view.SetBackgroundDrawable(bgDrawableNormal);
if ((marker != null))
{
marker.ShowInfoWindow();
}
endPressStatus = true;
return true;
}
else {
endPressStatus = false;
return false;
}
}
private Runnable ConfirmClickRunnable = new Java.Lang.Runnable(() =>
{
if (endPressStatus)
{
onClickConfirmed(view, marker);
}
});
/*private class RunnableAnonymousInnerClassHelper : Java.Lang.Object, Java.Lang.IRunnable
{
private readonly Context outerInstance;
public RunnableAnonymousInnerClassHelper(Context outerInstance)
{
this.outerInstance = outerInstance;
}
public void Run()
{
if (endPressStatus)
{
onClickConfirmed();
}
}
}*/
protected abstract void onClickConfirmed(View v, Marker marker);
}
}
Updated
I have implemented the Task.Factory.StartNew instead of Android Runnableand now I am stucking on the below lines. I am struggling on converting this below Java codes into C#since it is written by Anonymous class concept.
Java
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
infoButton in code is Call button
C# - Please help me to resolve the problem by converting/using(How to use) the above java code

The solution is too complicated for this window. Please see chat room for step by step solution.
https://chat.stackoverflow.com/rooms/128847/discussion-between-jamal-and-yuri-s

Related

I am not able to zoom camera in by animating google camera when i am using custom popup on click of marker

In on mapReady function of google map i have written
below: it basically forms cluster of marker location data and pass it
to the cluster manager
How can i do googleMap.animateCamera() on getInfoWindow() as it not working to get zoomed in by animating camera on click of marker
with popup opened.
mClusterManager = new ClusterManager<>(getActivity(), mMap);
mClusterManager.setAlgorithm(getAlgorithm());
mClusterManager.setRenderer(new MyRenderer(getActivity(), mMap));
mClusterManager.setAnimation(true);
//To set custom dialog on marker click
mClusterManager.getMarkerCollection().setInfoWindowAdapter(new PubLocationCustomClusterInfoView(this, getActivity(), pubArrayList, this, getMap()));
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<PubLocation>() {
#Override
public boolean onClusterItemClick(PubLocation item) {
return false;
}
});
PubLocationCustomClusterInfoView.java -- This is my custom view for
marker popup where i want to zoom in by animating google camera but im
unable to.
public class PubLocationCustomClusterInfoView implements GoogleMap.InfoWindowAdapter {
private View clusterItemView;
private static final String TAG = "PubLocationCustomCluste";
Context context;
private OnInfoWindowElemTouchListener infoButtonListener,orderFromPubListener;
ArrayList<PubData.Pub> pubArrayList;
MarkerInfoWindow markerInfoWindowlistner;
MapMarkerOnClickListener mapMarkerOnClickListener;
GoogleMap googleMap;
public PubLocationCustomClusterInfoView(MarkerInfoWindow markerInfoWindow, Context context, ArrayList<PubData.Pub> pubArrayList, MapMarkerOnClickListener mapMarkerOnClickListener,GoogleMap googleMap) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
this.context=context;
this.markerInfoWindowlistner=markerInfoWindow;
this.pubArrayList=pubArrayList;
clusterItemView = layoutInflater.inflate(R.layout.marker_info_window, null);
this.mapMarkerOnClickListener = mapMarkerOnClickListener;
this.googleMap=googleMap;
}
#Override
public View getInfoWindow(Marker marker) {
Log.i(TAG, "getInfoWindow: "+marker);
return null;
}
#Override
public View getInfoContents(Marker marker) {
Log.i(TAG, "getInfoContents: "+marker);
PubLocation pubLocation = (PubLocation) marker.getTag();
// googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(),13));
if (pubLocation == null) return clusterItemView;
TextView itemNameTextView = clusterItemView.findViewById(R.id.itemNameTextView);
TextView itemAddressTextView = clusterItemView.findViewById(R.id.itemAddressTextView);
ImageButton pub_info=(ImageButton)clusterItemView.findViewById(R.id.pub_info);
Button order_from_pub=(Button) clusterItemView.findViewById(R.id.order_from_pub);
this.infoButtonListener = new OnInfoWindowElemTouchListener(pub_info) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Log.i(TAG, "onClickConfirmed: ");
Intent intent=new Intent(context,PubInfoActivity.class);
intent.putExtra(Constants.PUB_ID_KEY, pubLocation.getPubId());
context.startActivity(intent);
}
};
pub_info.setOnTouchListener(infoButtonListener);
this.orderFromPubListener = new OnInfoWindowElemTouchListener(order_from_pub) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
for (int i = 0; i < pubArrayList.size(); i++) {
if (pubArrayList.get(i).getPubId().equals(pubLocation.getPubId())) {
mapMarkerOnClickListener.onMarkerClick(pubArrayList.get(i),v);
break;
}
}
}
};
order_from_pub.setOnTouchListener(orderFromPubListener);
itemNameTextView.setText(pubLocation.getTitle());
itemAddressTextView.setText(pubLocation.getSnippet());
markerInfoWindowlistner.setMarkerInfoWindow(clusterItemView,marker);
return clusterItemView;
}
}
Finally, got the solution to this issue
First set clustermanager to map as below:
getMap().setOnMarkerClickListener(mClusterManager);
On click of marker you just need to return true by adding one below condition and and pass zoom level to google map camera
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<PubLocation>() {
#Override
public boolean onClusterItemClick(PubLocation item) {
Log.i(TAG, "onClusterItemClick: ");
for (Marker marker : mClusterManager.getMarkerCollection().getMarkers()) {
if (marker.getPosition().latitude == item.getPosition().latitude &&
marker.getPosition().longitude == item.getPosition().longitude) {
marker.showInfoWindow();
}
}
CameraUpdate location = CameraUpdateFactory.newLatLngZoom(item.getPosition(), 10);
getMap().animateCamera(location, new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
getMap().animateCamera(CameraUpdateFactory.newLatLng(getMap().getProjection().fromScreenLocation(mappoint)));
}
#Override
public void onCancel() {
}
});
return true;
}
});

Vaadin Drag Drop Component

We are creating a web application using Vaadin. Our application contains alot of drag and drop features.
We have an object which is drag-able.
We can click on it to open its menu as well.
Sometimes that when we click that item it behaves as if it is dragged.
When this happens we are unable to open its menu because the component is in dragmode.
All components with the same functionality behave the same however in development environment, when we restart the tomcat the problem disappeared?
I noticed that when the components start showing me this behavior the webpage in FireFox the behavior is fine there?
A simple solution to this could be to introduce a drag mode/edit button which would allow the user to switch the drag mode on and off.
This would mean the user could interact with the components and then enter this "drag mode" when they wished to drag them. Hence reducing the frustration of trying to interact with the component and it starting to "drag" instead.
I've create a simple example program to try out below.
public class DemoUI extends UI {
HorizontalSplitPanel splitPanel;
DragAndDropWrapper wrapperA;
DragAndDropWrapper wrapperB;
DragAndDropWrapper splitPaneWrapper;
Button buttonA;
Button buttonB;
private boolean isDragMode = false;
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = DemoUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final HorizontalSplitPanel splitPanel = new HorizontalSplitPanel();
Button buttonA = new Button("Button A");
Button buttonB = new Button("Button B");
final DragAndDropWrapper wrapperA = new DragAndDropWrapper(buttonA);
final DragAndDropWrapper wrapperB = new DragAndDropWrapper(buttonB);
final VerticalLayout leftPanel = new VerticalLayout();
final VerticalLayout rightPanel = new VerticalLayout();
DragAndDropWrapper leftPanelWrapper = new DragAndDropWrapper(leftPanel);
DragAndDropWrapper rightPanelWrapper = new DragAndDropWrapper(rightPanel);
buttonA.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Notification.show("Button A was clicked");
}
});
buttonB.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Notification.show("Button B was clicked");
}
});
leftPanelWrapper.setDropHandler(new DropHandler() {
#Override
public void drop(DragAndDropEvent event) {
leftPanel.addComponent(event.getTransferable().getSourceComponent());
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
});
rightPanelWrapper.setDropHandler(new DropHandler() {
#Override
public void drop(DragAndDropEvent event) {
rightPanel.addComponent(event.getTransferable().getSourceComponent());
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
});
final Button dragMode = new Button("Drag Mode On");
dragMode.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
isDragMode = !isDragMode;
if (isDragMode) {
dragMode.setCaption("Drag Mode Off");
wrapperA.setDragStartMode(DragStartMode.WRAPPER);
wrapperB.setDragStartMode(DragStartMode.WRAPPER);
} else {
dragMode.setCaption("Drag Mode On");
wrapperA.setDragStartMode(DragStartMode.NONE);
wrapperB.setDragStartMode(DragStartMode.NONE);
}
}
});
leftPanel.setSizeFull();
rightPanel.setSizeFull();
leftPanelWrapper.setSizeFull();
rightPanelWrapper.setSizeFull();
leftPanel.addComponent(wrapperA);
rightPanel.addComponent(wrapperB);
splitPanel.setFirstComponent(leftPanelWrapper);
splitPanel.setSecondComponent(rightPanelWrapper);
splitPanel.setSizeFull();
VerticalLayout layout = new VerticalLayout();
layout.addComponent(dragMode);
layout.addComponent(splitPanel);
layout.setSizeFull();
this.setContent(layout);
this.setSizeFull();
}
.
All the best.

WP8 - How can I make the background agent execution to wait before all ImageOpened events are fired to update live tile with custom images?

How can I make the background agent execution to wait before all ImageOpened() events are fired (3 in this case) in order to update secondary live tile with custom images?
Edit 1:
In the OnInvoke() method of the ScheduledAgent I am calling my own create tile data function implemented in a shared library which in turn subscribes to 3 ImageOpened() events as I am trying to create custom images for all live tile templates i.e. small, medium and wide.
Since these being asynchronous events I have no way to check if all the events have completed successfully so that I can call NotifyComplete() to notify the background agent that its job is now done. So sometimes the tile gets updated while most of the times it doesn't. Also I am using the same function to update the live tiles every time the app is launched so there is no problem with its implementation. I have also tried to take care of all the memory limitations with the ScheduledAgent by disposing Bitmaps and calling GC.Collect() forcefully.
Please help in any possible way to fix this problem.
Add a new class that lets you create custom events -
public class SaveImageCompleteEventArgs : EventArgs
{
public bool Success { get; set; }
public Exception Exception { get; set; }
public string ImageFileName { get; set; }
public SaveImageCompleteEventArgs(bool success, string fileName)
{
Success = success;
ImageFileName = fileName;
}
}
Initialize the events and required variables in the file you are updating the custom live tile from -
public static int countTile = 3;
public event EventHandler<SaveImageCompleteEventArgs> SaveMediumImageComplete;
public event EventHandler<SaveImageCompleteEventArgs> SaveWideImageComplete;
public event EventHandler<SaveImageCompleteEventArgs> SaveSmallImageComplete;
public event EventHandler<SaveImageCompleteEventArgs> SaveAllImagesComplete;
Fire the completion event in the ImageOpened() event handlers for all the tiles and check if the SaveAllImagesComplete event needs to be fired-
public void OnBackgroundBmpOpenedMedium(object sender, RoutedEventArgs e)
{
if (SaveMediumImageComplete != null)
{
countTile -= 1;
CheckIfAllImagesOpened();
SaveMediumImageComplete(this, new SaveImageCompleteEventArgs(true, mediumTileImageUriIronMan));
}
}
private void CheckIfAllImagesOpened()
{
if (countTile == 0)
{
if (SaveAllImagesComplete != null)
{
var args1 = new SaveImageCompleteEventArgs(true, "");
SaveAllImagesComplete(this, args1);
}
}
}
In the ScheduledAgent file -
public static ManualResetEvent evt;
public bool IsPaused { get { return !evt.WaitOne(0); } }
In the OnInvoke() function -
evt = new ManualResetEvent(false);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//Initialize secondary tile here
if (secondaryTile != null)
{
/*
obj is a object of a helper file that contains all the
functions responsible for updating the custom live tile
Call the function that is responsible for initializing all the
tile image bitmpas and that subscribes to the ImageOpened events
*/
obj.SaveMediumImageComplete += async (s, args) =>
{
if (!IsPaused)
evt.Set();
};
obj.SaveWideImageComplete += async (s, args) =>
{
if (!IsPaused)
evt.Set();
};
obj.SaveSmallImageComplete += async (s, args) =>
{
if (!IsPaused)
evt.Set();
};
obj.SaveAllImagesComplete += async (s, args) =>
{
try
{
if (args.Success)
obj.UpdateTileIcon();
}
catch (Exception) { }
finally
{
if (!IsPaused)
evt.Set();
}
};
}
});
evt.WaitOne();
NotifyComplete();

My Libgdx game slow when integrated Admob

I am a new game developing with libgdx. I have a problem with Admob ads. When I call "adView.loadAd(adRequest);" my game is slowl, when I start game, FPS ~ 60 , when I call adView.loadAd(adRequest) my game is slowly FPS ~ 30.
Here is my
public class MainActivity extends AndroidApplication implements IActivityRequestHandler {
protected AdView adView;
AdRequest adRequest;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
protected Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_ADS: {
System.out.println("SHOW ADVIEW");
adView.setVisibility(View.VISIBLE);
break;
}
case HIDE_ADS: {
adView.setVisibility(View.GONE);
break;
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libgdx View
View gameView = initializeForView(new MyGdxGame(this), false);
// Create and setup the AdMob view`enter code here`
adView = new AdView(this, AdSize.BANNER, "XXXXXX"); // Put in your
// secret key
// here
adRequest = new AdRequest();
adView.loadAd(adRequest);
// adView.loadAd(new AdRequest());
// Add the libgdx view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}
// This is the callback that posts a message for the handler
#Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
I read topic Using interstitials from Admob in a Libgdx game for Android, it's slow when dismissing it
but not solution
Please help me if you have a solution.
This is a known issue and at the moment you cant change it.
Post at the libgdx Forum
It has nothing todo with your code. I think

JTree and dropdown options on right clicking nodes

I'm trying to use the JTree and implement different drop downs for all the parent nodes and the children nodes.
Here's what I've done:
pmTree.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
if(evt.getButton() == evt.BUTTON1) {
}
else if (evt.getButton() == evt.BUTTON3) {
TreePopup(evt);
//pmTree.updateUI();
}
}catch (Exception e) {}
}
});
and PopupCode:
public void TreePopup(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) pmTree.getLastSelectedPathComponent();
popup = new JPopupMenu();
popup.setInvoker(pmTree);
PopupHandler handler = new PopupHandler(pmTree, popup);
if(node.getLevel() == 1)
{
popup.add(getMenuItem("Parent Node", handler));
}
else if(node.getLevel() == 2)
{
popup.add(getMenuItem("Child", handler));
}
}
and PopUpHandler:
public class PopupHandler extends javax.swing.JFrame implements ActionListener {
JPopupMenu popup;
Point loc;
public PopupHandler(JTree tree, JPopupMenu popup) {
//this.tree = NewJFrame.pmTree;
this.popup = popup;
tree.addMouseListener(ma);
}
and also the
public void actionPerformed(java.awt.event.ActionEvent evt)
for the Child or Parent node being clicked.
However, when I run the program, I get the SAME right click popups for both the child and parent node.
Sorry for the huge chunk of code. I've been stuck with it for 2 days and yet not successful.
Thanks!
Don't go as low-level as a MouseListener, instead use the api around componentPopupMenu. Doing so, the general approach is dynamically configure the componentPopup in the getPopupLocation method, some simple example snippet:
JPopupMenu popup = new JPopupMenu();
final Action action = new AbstractAction("empty") {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
popup.add(action);
JTree tree = new JTree() {
/**
* #inherited <p>
*/
#Override
public Point getPopupLocation(MouseEvent e) {
if (e != null) {
// here do your custom config, like f.i add/remove menu items based on context
// this example simply changes the action name
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
action.putValue(Action.NAME, String.valueOf(path.getLastPathComponent()));
return e.getPoint();
}
action.putValue(Action.NAME, "no mouse");
return null;
}
};
tree.setComponentPopupMenu(popup);
You check the selected node:
DefaultMutableTreeNode node = (DefaultMutableTreeNode)pmTree.getLastSelectedPathComponent();
to see if you have a "parent" or a "child" node. You should select the node at the mouse position first, otherwise it will not be the right node. Call
TreePath path = pmTree.getPathForLocation(evt.getX(), evt.getY());
if (path != null) {
pmTree.setSelectionPath(path);
} else {
return;
}
at the beginning of treePopup. (methods in Java should start with a lower case letter!)
Awesome. I was successfully able to put the setSelectionPath() call inside the override of getPopupLocaiton(). I had been trying to do it inside the ActionListener of my JMenuItem to no avail.
public Point getPopupLocation( MouseEvent e ) {
Point point = null;
if( e != null ) {
TreePath path = getClosestPathForLocation( e.getX(), e.getY() );
setSelectionPath( path );
point = e.getPoint();
}
return point;
}