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

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;
}
});

Related

Map fragment doesn't move to current location when Recreated

Greetings to the community. This is my first question, please guide me if I did any mistake.
I have four fragments in my app. An activity(Main Activity) that hosts all the four fragments.
Google Maps Fragment
Fragment two
Fragment three
Fragment four
When the application starts. Maps fragment is loaded and it shows marker at my current location. But when I move from Maps fragment to Fragment two and then came back to Map Fragment it doesn't show my current location
Here is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Fragments
private MapsFragment mapsFragment = new MapsFragment();
private QrScanFragment qrScanFragment = new QrScanFragment();
private SeatsFullFragment seatsFullFragment = new SeatsFullFragment();
private EmergencyFragment emergencyFragment = new EmergencyFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLayouts();
initListeners();
// Maps Fragment Loaded
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
loadFragment(mapsFragment);
}
}
loadFragment(Fragment fragment)
public void loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
}
}
Moving b/w fragments
if (view == mLlMaps) {
if (!mapsFragment.isVisible()) {
loadFragment(mapsFragment);
mTvTitle.setText("Map");
}
mIvMaps.setImageResource(R.drawable.ic_map_pin_2_line_fill);
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
} else if (view == mLlQrScan) {
if (!qrScanFragment.isVisible()) {
loadFragment(qrScanFragment);
mTvTitle.setText("ScanQR");
}
mIvQrScan.setImageResource(R.drawable.ic_baseline_qr_code_scanner_24_fill);
mIvQrScan.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
}
}
MapsFragment.java
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private SupportMapFragment mapFragment;
// To get Current Location of Driver
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_maps, container, false);
buildLocationRequest(); // Request for current Location
buildLocationCallback(); // When location is provided
updateLocation(); // Fused Location Provider
// Child Fragment Manager copied from Uber
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
// Request for current Location
private void buildLocationRequest() {
if (locationRequest == null) {
locationRequest = new LocationRequest();
locationRequest.setSmallestDisplacement(50f); // 50m
locationRequest.setInterval(15000); // 15s
locationRequest.setFastestInterval(10000); // 10s
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
// When location result is provided
private void buildLocationCallback() {
if (locationCallback == null) {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),
locationResult.getLastLocation().getLongitude());
// 18f is the radius of circle
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 18f));
}
};
}
}
// Fused Location Provider
private void updateLocation() {
if (fusedLocationProviderClient == null) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Permission Required", Toast.LENGTH_SHORT).show();
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("EB", "onMapReady: called");
// Check Permission
Dexter.withContext(getContext())
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Toast.makeText(getContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
}
fusedLocationProviderClient.getLastLocation().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
LatLng userLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
// 18f is the radius of circle
mMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(userLatLng, 18f));
}
});
return true;
}
});
// Set Layout - Location Button
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1"))
.getParent())
.findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
//Right Bottom
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 0, 50);
// Move to current Location
buildLocationRequest();
buildLocationCallback();
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(),
"Permission" + permissionDeniedResponse.getPermissionName() + "wasdenied",
Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
// Change/Parse the Maps Style
try {
boolean success = googleMap.setMapStyle(MapStyleOptions
.loadRawResourceStyle(getContext(), R.raw.uber_maps_style));
if (!success)
Log.e("Error", "Style parsing Error");
} catch (Resources.NotFoundException e) {
Log.e("Error", e.getMessage());
}
}
}

Add custom wms layer to codename one Mapcontainer

I am building an android GPS app with Codename one. I use com.codename1.googlemaps.MapContainer to create a Google map;
In my app is use tabs to create different "pages".
Code:
cnt = new MapContainer();
t.addTab("Tab3", cnt);
And for my current location I use:
try {
Coord position = new Coord(lat,lng);
cnt.clearMapLayers();
cnt.setCameraPosition(position);
cnt.addMarker(EncodedImage.create("/maps-pin.png"), position, "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// stuff todo...
}
});
} catch(IOException err) {
// since the image is iin the jar this is unlikely
err.printStackTrace();
}
I like to add a wms layer to the Google Maps. Is this possible? I can't find in codenameone a command addLayer. If yes, do you have a code snippet how to do this?
If it is not possiple, can I use openlayers in my codename one app? Can you give me a code snippet to do this?
Edit
I started to create an native file to "catch"the addtileoverlay from google maps api. The layer I want to use is a xyz layer, so I think I can use a urltileprovider from the googlemap api
I made the native code for the tileoverlay but the tileoverlay doesn't appear. Is it because i didn't get a link with the mapcontainer.
I am little bit stuck. I tried to build from scratch with the googmaps example but the mapcompnent is not anymore used.
package com.Bellproductions.TalkingGps;
import com.google.android.gms.maps.model.UrlTileProvider;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.TileOverlay;
import com.codename1.impl.android.AndroidNativeUtil;
import java.util.Locale;
import java.net.MalformedURLException;
public class SeamarksImpl {
private GoogleMap mapInstance;
private TileOverlay m;
TileProvider provider;
public boolean isSupported() {
return true;
}
public long addTilelayer (){
final String URL_FORMAT = "http://t1.openseamap.org/seamark/{z}/{x}/{y}.png";
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
provider = new UrlTileProvider(256, 256) {
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
try {
y = (1 << zoom) - y - 1;
return new URL(String.format(Locale.US, URL_FORMAT, zoom, x, y ));
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}
TileOverlayOptions tileopt = new TileOverlayOptions().tileProvider(provider);
public void addlayer() {
m = mapInstance.addTileOverlay(tileopt);
}
};
}
});
long p = 1;
return p;}
}
My seamarks.java file has this code to bind with the native interface
import com.codename1.system.NativeInterface;
/**
*
* #author Hongerige Wolf
*/
public interface Seamarks extends NativeInterface {
public void addTilelayer ();
}
In the mainactivity java file i have the statements
public Seamarks seamark;
public void init(Object context) {
seamark = (Seamarks)NativeLookup.create(Seamarks.class);
}
public void start() {
seamark.addTilelayer();
}
Update
I created a new googlemaps.CN1lib. But the xyz layer is not showing on the googlemaps. I used native code tot use the Tileoverlay feature and tried to add tileoverlay in the same way as Markers.
In the InternalNativeMapsImpl file i changed
private void installListeners() {
/*
if (mapInstance == null) {
view = null;
System.out.println("Failed to get map instance, it seems google play services are not installed");
return;
}*/
view.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mapInstance = googleMap;
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
String tileLayer= "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
//String s = String.format(Locale.US, tileLayer , zoom, x, y);
String s = tileLayer + "/" + zoom + "/" + x + "/" + reversedY + ".png";
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
mapInstance.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
Long val = listeners.get(marker);
if (val != null) {
MapContainer.fireMarkerEvent(InternalNativeMapsImpl.this.mapId, val.longValue());
return true;
}
return false;
}
});
mapInstance.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
public void onCameraChange(CameraPosition position) {
MapContainer.fireMapChangeEvent(InternalNativeMapsImpl.this.mapId, (int) position.zoom, position.target.latitude, position.target.longitude);
}
});
mapInstance.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireTapEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireLongPressEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setMyLocationEnabled(showMyLocation);
mapInstance.getUiSettings().setRotateGesturesEnabled(rotateGestureEnabled);
}
});
}
Secondly i added a addTilexyz method also in the same way as addMarkers
public long addTilexyz(final String Turl) {
uniqueIdCounter++;
final long key = uniqueIdCounter;
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
// Tileurl = "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
String s = String.format(Locale.US, Turl , zoom, x, reversedY);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
}
});
return key;
}
In the InternalNativeMaps file i added te method
public long addTilexyz(String Turl);
And in the Mapcontainer file i added
public MapObject addTilexyz(String Turl) {
if(internalNative != null) {
MapObject o = new MapObject();
Long key = internalNative.addTilexyz(Turl);
o.mapKey = key;
markers.add(o);
return o;
} else {
}
MapObject o = new MapObject();
return o;
}
I am puzzeled what is wrong with the code. I wonder if the commands
Long key = internalNative.addTilexyz(Turl);
and
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
put the tileoverlay on the googlemap. Or is the tileurl wrong. http://t1.openseamap.org/seamark/z/x/y.png is correct.
We don't expose layers in the native maps at this time, you can fork the project and just add an API to support that to the native implementations.

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

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

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.

How to run a javaFX MediaPlayer in swing?

I've made a simple Media Player for an application I'm working on, the problem is that I thought that you could simply integrate JavaFX into Swing. Which is not the case. I have been searching for a solution to this problem and tried to use this website: http://docs.oracle.com/javafx/2/swing/jfxpub-swing.htm
The problem is that even though I have the website that explains how to put the code together, I still don't understand how. Here is the mediaplayer and I plan to integrate it into my Swing code, so that I can call the media player when a button is clicked. Here is all my code for the media player and if anyone can share some light on how to integrate it into my Swing code i.e my GUI, I would probably have to kiss you through the computer.
public class Player extends Application{
private boolean atEndOfMedia = false;
private final boolean repeat = false;
private boolean stopRequested = false;
private Duration duration;
private Label playTime;
private Slider volumeSlider;
#Override
public void start(final Stage stage) throws Exception {
stage.setTitle("Movie Player");//set title
Group root = new Group();//Group for buttons etc
final Media media = new Media("file:///Users/Paul/Downloads/InBruges.mp4");
final MediaPlayer playa = new MediaPlayer(media);
MediaView view = new MediaView(playa);
//Slide in and out and what causes that.
final Timeline slideIn = new Timeline();
final Timeline slideOut = new Timeline();
root.setOnMouseEntered(new javafx.event.EventHandler<javafx.scene.input.MouseEvent>() {
#Override
public void handle(MouseEvent t) {
slideIn.play();
}
});
root.setOnMouseExited(new javafx.event.EventHandler<javafx.scene.input.MouseEvent>() {
#Override
public void handle(MouseEvent t) {
slideOut.play();
}
});
final VBox vbox = new VBox();
final Slider slider = new Slider();
final Button playButton = new Button("|>");
root.getChildren().add(view);
root.getChildren().add(vbox);
vbox.getChildren().add(slider);
vbox.getChildren().add(playButton);
vbox.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 400, 400, Color.BLACK);
stage.setScene(scene);
stage.show();
// Play/Pause Button
playButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
Status status = playa.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED)
{
// don't do anything in these states
return;
}
if ( status == Status.PAUSED
|| status == Status.READY
|| status == Status.STOPPED)
{
// rewind the movie if we're sitting at the end
if (atEndOfMedia) {
playa.seek(playa.getStartTime());
atEndOfMedia = false;
}
playa.play();
} else {
playa.pause();
}
}
});
//Listeners and Shit for Play Button
playa.setOnPlaying(new Runnable() {
#Override
public void run() {
if (stopRequested) {
playa.pause();
stopRequested = false;
} else {
playButton.setText("||");
}
}
});
playa.setOnPaused(new Runnable() {
#Override
public void run() {
playButton.setText(">");
}
});
playa.play();
playa.setOnReady(new Runnable() {
#Override
public void run(){
int v = playa.getMedia().getWidth();
int h = playa.getMedia().getHeight();
stage.setMinWidth(v);
stage.setMinHeight(h);
vbox.setMinSize(v, 100);
vbox.setTranslateY(h-50);
//slider and graphical slide in/out
slider.setMin(0.0);
slider.setValue(0.0);
slider.setMax(playa.getTotalDuration().toSeconds());
slideOut.getKeyFrames().addAll(
new KeyFrame(new Duration(0),
new KeyValue(vbox.translateYProperty(), h-100),
new KeyValue(vbox.opacityProperty(), 0.9)
),
new KeyFrame(new Duration(300),
new KeyValue(vbox.translateYProperty(), h),
new KeyValue(vbox.opacityProperty(), 0.0)
)
);
slideIn.getKeyFrames().addAll(
new KeyFrame(new Duration(0),
new KeyValue(vbox.translateYProperty(), h),
new KeyValue(vbox.opacityProperty(), 0.0)
),
new KeyFrame(new Duration(300),
new KeyValue(vbox.translateYProperty(), h-100),
new KeyValue(vbox.opacityProperty(), 0.9)
)
);
}
});
//Slider being current and ability to click on slider.
playa.currentTimeProperty().addListener(new ChangeListener<Duration>(){
#Override
public void changed(ObservableValue<? extends Duration> observableValue, Duration duration, Duration current){
slider.setValue(current.toSeconds());
}
});
slider.setOnMouseClicked(new javafx.event.EventHandler<javafx.scene.input.MouseEvent>() {
#Override
public void handle(javafx.scene.input.MouseEvent t) {
playa.seek(Duration.seconds(slider.getValue()));
}
});
}
Use JFXPanel:
public class Test {
private static void initAndShowGUI() {
// This method is invoked on Swing thread
JFrame frame = new JFrame("FX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setVisible(true);
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
}
});
}
private static void initFX(JFXPanel fxPanel) {
// This method is invoked on JavaFX thread
Scene scene = createScene();
fxPanel.setScene(scene);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initAndShowGUI();
}
});
}
}
where method createScene() is start(final Stage stage) from your code.
Just instead of putting scene to stage you return it.