InfoWindow Content Click is not working for layouts In Android - android

I'm using google map in my application ,when I click the marker info-window is opened again I want to click the info-window layout but its not working for layouts.If I give click listener for button means its working.Please help me to fix this issue.
Activity:
public class SampleFragment1 extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet,userNameTV,loggedLabel,userLastNameTV,time,distance,tasks;
private Button infoButton, infoButton2;
private OnInfoWindowElemTouchListener infoButtonListener;
LinearLayout markerlay;
GoogleMap mMap;
public void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private MapView mapView;
private MarkerOptions mMarker;
MapWrapperLayout mapWrapperLayout;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.con_fragment_google, container, false);
mapWrapperLayout = (MapWrapperLayout)view.findViewById(R.id.map_relative_layout);
mapView = (MapView)view. findViewById(R.id.mapView);
// getContext().startService(new Intent(getContext(),GPSTracker.class));
mapView.onCreate(savedInstanceState);
buildGoogleApiClient();
createLocationRequest();
mapView.getMapAsync(this);
return view;
}
private synchronized void buildGoogleApiClient() {
try {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
// to get current latitude and longitude
// storing the updated latitde and longitude when user moving and reach destination
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mapWrapperLayout.init(mMap, getPixelsFromDp(getContext(), 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getActivity().getLayoutInflater().inflate(R.layout.info_widow_layout, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.nametv);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.addressTv);
this.infoButton = (Button)infoWindow.findViewById(R.id.clinicType);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoTitle
) //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(getContext(), marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoTitle.setOnTouchListener(infoButtonListener);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
Note:Here I give click listener for textview ,the textview present inside the layout.

Related

Marker not moving on Google MapView

I implement google map view inside fragment, everything is working but Marker is not moving into new location its fixed. I tried long press,listeners,tapping on other part of map, Nothing works.
MapView Fragment
public class MapLocation_Fragment extends Fragment implements GoogleMap.OnMarkerDragListener,GoogleMap.OnMarkerClickListener,OnMapReadyCallback {
MapView mapView;
GoogleMap google_Map;
Marker Map_marker;
LatLng locclPosition;
double lati,longi;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.maplocation_fragment, container, false);
mapView = (MapView) view.findViewById(R.id.send_Location_MapView);
mapView.onCreate(savedInstanceState);
mapView.onResume();// Needed tog et the map to display immediately
lati=getArguments().getDouble("lat");
longi=getArguments().getDouble("longi");
locclPosition=new LatLng(lati,longi);
MapsInitializer.initialize(getActivity());
mapView.getMapAsync(this);
return view;
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMarkerDragStart(Marker marker) {
Map_marker=marker;
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onMapReady(GoogleMap googleMap) {
google_Map = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
google_Map.setOnMarkerClickListener(MapLocation_Fragment.this);
google_Map.setOnMarkerDragListener(MapLocation_Fragment.this);
google_Map.setTrafficEnabled(true);
google_Map.setBuildingsEnabled(true);
google_Map.setMapType(googleMap.MAP_TYPE_NORMAL); //THIS OPTION WILL SHOW MAP IN SATELLITE FORM
google_Map.addMarker(new MarkerOptions()
.position(locclPosition)
.title("Current Location")
.draggable(true));
CameraPosition cameraPosition=new CameraPosition.Builder().target(locclPosition).zoom(19).build();
google_Map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
I need to marker to move where ever user tap on map but after lot of effort its still not moving at all. Please help guys.
To make your marker move when dragging it you need to write some code in your onMarkerDragEnd method, basically to update the position of your marker (locclPosition) to where the dragging ends (new coordinates)
#Override
public void onMarkerDragEnd(Marker marker) {
locclPosition = marker.getPosition();
}

NavigationDrawer + Google maps event

I have a problem with pressing an option in my navigationView (R.id.create_marker) I want to create a marker in my MapFragment, but I can not do it, any suggestions?
Code of MainActivity.java where I press the menu option:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.create_marker:
Toast.makeText(MainActivity.this, "Crear Marker", Toast.LENGTH_SHORT).show();
// Create marker and display it on the map
break;
}
return false;
}
});
Code of MapFragment.java:
public class MapFragment extends Fragment
implements OnMapReadyCallback {
private View rootView;
private GoogleMap gMap;
private MapView mapView;
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_map, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) rootView.findViewById(R.id.map);
if (mapView != null) {
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
This is the structure of my project:
To create a marker, you need to call addMarker method on your Map, once it's ready to be used.
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions().position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
If you want your Map to open a marker for a fixed Lat-Lng, pass in the coordinates as shown in the code above, otherwise request location via Google Location Api and pass the obtained Lat-Lng values to the addMarker() method.

Retrieve a GoogleMap from a fragment in backstack

I've a class "MainActivity" which calls the different fragments in particular a fragment which display a GoogleMap called MapsFragment.
When this fragment is called for the first time, I had some markers (which are refresh every timeToRefresh. The method startDrawingBomb() is called from the MainActivity class) and everything works perfectly when the user do not change to another fragment.
When a user ask to move to an other fragment I save the the MapsFragment created before in the backStack of the MainActivity (to retrieve it later)
The problem happens when I call this MapsFragment a second time, the fragment is displaying the map but not all the markers I've added before.
I imagine it's because the MapView, and the GoogleMap created by the MapsFragment are not the same as before.
My question is : How can I retrieve the map that I draw before easily ? Or I had to stop all my threads (in onPause() for example), create a new MapsFragment, obtain a new MapView, a new GoogleMap object and apply again all the previous threads ?
This is a part of my MapsFragment :
public class MapsFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private OnMessageListener mCallback;
private GoogleMap _googleMap;
private MapView mMapView;
private ArrayList<Marker> markerArrayListScout = new ArrayList<>();
private ArrayList<Circle> markerArrayListBomb= new ArrayList<>();
private ArrayList<String> idToCircleId = new ArrayList<>();
private ArrayList<Integer> idArray = new ArrayList<>();
private boolean isfirstLocation = true;
boolean mustBeScoutLocationEnabled;
boolean mustDrawCircle;
public MapsFragment(){
super();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("MAPS_FRAGMENT","onCreate() called");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("MAPS_FRAGMENT","onCreateView() called");
View rootView = inflater.inflate(R.layout.map, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
Log.v("MAPS_FRAGMENT","onMapReady() called");
_googleMap = googleMap;
_googleMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.v("Location","onConnected");
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
//Execute location service call if user has explicitly granted ACCESS_FINE_LOCATION..
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.v("Location","onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.v("Location","onConnectionFailed");
}
#Override
public void onLocationChanged(Location location) {
Log.v("Location","location : " + location.toString());
// Add a marker and move the camera
if(isfirstLocation) {
LatLng currentLat = new LatLng(location.getLatitude(), location.getLongitude());
_googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentLat));
_googleMap.moveCamera(CameraUpdateFactory.zoomTo(19));
isfirstLocation = false;
}
//if(mCallback != null)
mCallback.onUpdateLocation(location.getLatitude(),location.getLongitude());
}
/**
* Draw Bomb and update its view all the timeToRefresh milliseconds.
* #param timeToRefresh the time in milliseconds which the marker needs to refresh
* #param id the id of the current bomb we need to work with
*/
public void startDrawingBomb(final int timeToRefresh,final int id){
mustDrawCircle = true;
Log.v("JOSE","passe1");
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
while (mustDrawCircle) {
Log.v("JOSE","update bomb");
mCallback.updateBombs();
//Log.v("JOSE","bomb updated ?");
Thread.sleep(timeToRefresh);
// This method is called from the MainActivity
final CircleOptions circleOptions = mCallback.drawBombCircle(id);
final String idToCompare = getIdCircle(id);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
boolean isCenterSet = false;
if (circleOptions != null) {
Log.v("JOSE","size marker : " +markerArrayListBomb.size());
for(int i=0;i<markerArrayListBomb.size();i++){
Log.v("JOSE","Id to compare : " +idToCompare);
Log.v("JOSE","Id markearray : " +markerArrayListBomb.get(i).getId());
if((markerArrayListBomb.get(i).getId()).equals(idToCompare)){
// si c'est la même chose, il suffit de updater
markerArrayListBomb.get(i).setCenter(circleOptions.getCenter());
markerArrayListBomb.get(i).setVisible(true);
isCenterSet = true;
}
}
// il faut creer une nouvelle bombe
if(!isCenterSet) {
Circle newCircle = _googleMap.addCircle(circleOptions);
markerArrayListBomb.add(newCircle);
newIdCircle(id, newCircle.getId());
//Log.v("JOSE", "New bomb drawn id : " + newCircle.getId());
}
}
}
});
}
String idToCompare = getIdCircle(id);
for(int i=0;i<markerArrayListBomb.size();i++){
if((markerArrayListBomb.get(i).getId()).equals(idToCompare)){
final int index = i;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
markerArrayListBomb.get(index).setVisible(false);
}
});
}
}
}
catch (InterruptedException e){
e.printStackTrace();
}
}
});
thread.start();
}
public void cancelDrawingBomb(){mustDrawCircle = false;}
// Container Activity must implement this interface
public interface OnMessageListener {
public void onUpdateLocation(double lat,double lon);
public void getAllOtherScoutsLocation();
public void updateBombs();
public CircleOptions drawBombCircle(int id);
}
/**
*
* #param id de la bombe dans la classe Bomb
* #return le cercle créé associé. Sinon, return null
*/
private String getIdCircle(int id){
if(idArray.size() == 0)
return null;
for(int i=0 ; i<idArray.size();i++){
if(idArray.get(i) == id)
return idToCircleId.get(i);
}
return null;
}
/**
* Si une bombe est supprimée, il faut appeler cette méthode
* #param id
*/
private void removeIdCircle(int id){
for(int i=0 ; i<idArray.size();i++){
if(idArray.get(i) == id) {
idToCircleId.remove(i);
idArray.remove(i);
}
}
}
/**
* A appeler à chaque fois u'une bombe est créée
* #param id l'id de la classe BOMB
* #param ids l'id créé grâce à la classe Circle de google
*/
private void newIdCircle(int id,String ids){
idToCircleId.add(ids);
idArray.add(id);
}
}
And this how I called the second time my MapsFragment :
if (id == R.id.map) {
if(fragmentManager.findFragmentByTag(MAPS_FRAGMENT) != null){
MapsFragment fragment = (MapsFragment)fragmentManager.findFragmentByTag(MAPS_FRAGMENT);
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment,MAPS_FRAGMENT).addToBackStack(MAPS_FRAGMENT).commit();
}
}
Thanks a lot everyone, and sorry for my bad English.
If you want more information, or a better explanation, don't hesitate to tell me !
Implement save to bundle functionality at Onpause() for your MapFragment. Then in onCreateView() always check your bundle.
If the bundle is empty then it's a new fragment. If the bundle is not empty this means it was previously created.
Hope this helps :
For saving and restoring to bundle : Saving Android Activity state using Save Instance State

Google maps loading slow inside fragment

I have main activity with fragments and one of the fragments is Map Fragment. Now, when i tap there, every time it opens slow. I am using singleton instance of fragment, but it still doesnt work as expected. Here is a good of that class:
public MapsFragment() {
gson = new Gson();
}
public static MapsFragment getInstance() {
if (mInstance == null)
mInstance = new MapsFragment();
return mInstance;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_maps, container, false);
mOnSavedinstance = savedInstanceState;
mMapView = (MapView) v.findViewById(R.id.map);
mMapWrapperLayout = (MapWrapperLayout) v.findViewById(R.id.map_relative_layout);
mMapView.getMapAsync(MapsFragment.this);
mMapView.onCreate(savedInstanceState);
mMapView.requestFocus();
MapsInitializer.initialize(getActivity());
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mMapWrapperLayout.init(mGoogleMap, Constants.MARKER_HEIGHT);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mGoogleMap.setMyLocationEnabled(false);
}
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
setUpMap();
}
private void setUpMap() {
new Thread(new Runnable() {
#Override
public void run() {
final ArrayList<MarkerOptions> markerOptionses = new ArrayList<MarkerOptions>();
int counter = 0;
for (final Places places : Model.getInstance().getPlaces()) {
LatLng location = new LatLng(Double.parseDouble(places.getLat()), Double.parseDouble(places.getLon()));
final MarkerOptions options = new MarkerOptions();
options.snippet(gson.toJson(places));
options.position(location);
options.title(String.valueOf(counter));
markerOptionses.add(options);
counter++;
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (MarkerOptions markerOptionse : markerOptionses) {
mGoogleMap.addMarker(markerOptionse).setIcon(BitmapDescriptorFactory.fromResource(Model.getInstance().getPlaces()
.get(Integer.parseInt(markerOptionse.getTitle())).getMapsRes(getActivity())));
}
}
});
final CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(45.4654, 9.1859)) // Sets the center of the map to location user
.zoom(Constants.CAMERA_ZOOM_LOCATION) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnMapClickListener(MapsFragment.this);
// mGoogleMap.setOnInfoWindowClickListener(mInfoListener);
}
});
}
}).start();
}
#Override
public void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleMap.clear();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
You can try to add markers only if it would be visible? I mean: first move camera to start position and set zoomLevel and just after that add Markers but only if it's in visible sector. And update markers on camera move.

Google Map fragment shows the previous fragment's element

Title can be a bit complicated but the problem is literally as described. I'm trying to use google map fragment within a fragment stack. When the application starts the user will see a button and when the user pushes the button, current view will be replaced with map fragment. Currently, I'm able to replace the fragments but when the map fragment is shown, the view still has the button of previous fragment.Also I'm trying to replace fragments in one of the tabs of my app. Here is my code;
Map Fragment;
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_maps, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
try {
googleMap.setMyLocationEnabled(true);
} catch (SecurityException e) {
e.printStackTrace();
}
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Home Fragment;
public class HomeFragment extends RootFragment {
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the shared Tracker instance.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab, container, false);
Button go = (Button)v.findViewById(R.id.btn_go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(getActivity(), MapFragment.class);
//startActivity(intent);
enterNextFragment();
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
private void enterNextFragment() {
// Pushing MapView Fragment
Fragment fragment = Fragment.instantiate(this.getContext(), MapFragment.class.getName());
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_mainLayout, fragment);
ft.commit();
}
}
Map Layout;
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Home Fragment;
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment"
android:background="#android:color/white"
android:id="#+id/fragment_mainLayout">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_go"
android:layout_width="fill_parent"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:layout_marginTop="170dp"
android:text="GO"/>
</FrameLayout>
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Your fragments shouldn't communicate directly according to the documentation.
If you've managed to communicate with your fragments considering the documentation. Then you can use this simple method to be able to change and reuse any fragment.
In your host activity :
private void changeFragment(Fragment frag, boolean saveInBackstack) {
String backStateName = ((Object) frag).getClass().getName();
try {
FragmentManager manager = getSupportFragmentManager();
if (manager.findFragmentByTag(backStateName) == null) {
//fragment not in back stack, create it.
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, frag, backStateName);
if (saveInBackstack) {
Log.d(TAG, "Change Fragment: addToBackTack " + backStateName);
transaction.addToBackStack(backStateName);
} else {
Log.d(TAG, "Change Fragment: NO addToBackTack");
}
transaction.commit();
} else {
manager.popBackStack();
}
} catch (IllegalStateException exception) {
Log.w(TAG, "Unable to commit fragment, could be activity as been killed in
}
}
just add android:background="#android:color/white" on the main view of the map_layout xml file
Here is the solution;
Home Fragment;
public class HomeFragment extends RootFragment {
private LocationManager locationManager;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Obtain the shared Tracker instance.
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_tab, container, false);
Button go = (Button) v.findViewById(R.id.btn_go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), MapFragment.class);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//Toast.makeText(getContext(), "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
}
MapFragment (it is now fragmentActivity not fragment);
public class MapFragment extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
LocationListener {
MapView mMapView;
private GoogleMap googleMap;
// private GoogleMap map;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private Marker marker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(this.getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = null;
try {
googleMap.setMyLocationEnabled(true);
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
} catch (SecurityException e) {
e.printStackTrace();
}
if (location != null) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}

Categories

Resources