Zoom to the current location not working with navigation drawer - android

I'm developing an Android Application which is consists of a Navigation drawer and a Google Map. I have successfully developed my Navigation Drawer and connect my Map into it. The thing is I need my Map to Zoom to the current location.
Here is the code I used in MapsActivity.java.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Identify the current location of the device
mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving
Location currentLocation = getMyLocation(); // Calling the getMyLocation method
if(currentLocation!=null){
LatLng currentCoordinates = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13.0f));
}
}
Here I implemented getMyLocation() method.
//Zoom to the current location
private Location getMyLocation() {
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Location wasn't found, check the next most accurate place for the current location
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
// Finds a provider that matches the criteria
String provider = lm.getBestProvider(criteria, true);
// Use the provider to get the last known location
myLocation = lm.getLastKnownLocation(provider);
}
return myLocation;
}
Here is How I gave MapsFragment in to NavigatioDrawerActivity.
fragment = new MapFragment();
When I run this alone (Insert intent filter to MapsActivity in Manifest) it works perfect. But, when I'm running the Nvigation Drawer as MainActivity this function is not working. Only the default Map is loading.
What should I do?
-edit-
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
My Maps.xml is like this.
<fragment 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"
android:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
My whole MapsActivity.java
public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private MapView mapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true); // Identify the current location of the device
mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving
initializaMap(rootView, savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void initializaMap(View rootView, Bundle savedInstanceState){
MapsInitializer.initialize(MapsActivity.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapsActivity.this)) {
case ConnectionResult.SUCCESS:
mapView = (MapView) rootView.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9270786, 79.861243), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onMyLocationChange(Location location) {
}
}
Here is my NavigationDrawer.java
public class NavigationDrawer extends ActionBarActivity {
private GoogleMap mMap;
String[] menutitles;
TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
private LinearLayout mLenear;
static ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_NavigationDrawer);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
mLenear = (LinearLayout)findViewById(R.id.left_drawer);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFA500")));
imageView=(ImageView)findViewById(R.id.profPic);
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.ic_prof);
imageView.setImageBitmap(getCircleBitmap(bitmap));
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId( i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu(); }
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
initializaMap(savedInstanceState);
}
private void initializaMap(Bundle savedInstanceState){
MapsInitializer.initialize(Extract.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(Extract.this)) {
case ConnectionResult.SUCCESS:
MapView mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9192, 79.8950), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
//Circle Image
public static Bitmap getCircleBitmap(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int radius = Math.min(h / 2, w / 2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Bitmap.Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Paint.Style.FILL);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
c.drawBitmap(bitmap, 4, 4, p);
p.setXfermode(null);
p.setStyle(Paint.Style.STROKE);
p.setColor(Color.WHITE);
p.setStrokeWidth(3);
c.drawCircle((w / 2) + 2, (h / 2) + 2, radius, p);
return output;
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
Fragment fragment = null;
switch (position) {
case 0:
// fragment = new MapFragment();
//break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mLenear);
}
else {
// error in creating fragment
Log.e("Extract", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_extract, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default :
return super.onOptionsItemSelected(item);
}
}
/*** * Called when invalidateOptionsMenu() is triggered */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState(); }
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}

try this ..
map.animateCamera(CameraUpdateFactory.newLatLngZoom((sydney), 13.0f));
you have not given by in float. so its not working.. try this..

try this
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13));
In XML
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In JAVA Activity
private void initializaMap(Bundle savedInstanceState){
MapsInitializer.initialize(MainActivity.this);
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
if (mapView != null) {
mMap = mapView.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings mUiSettings = mMap.getUiSettings();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f));
mUiSettings.setCompassEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 13));
}
break;
case ConnectionResult.SERVICE_MISSING:
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
break;
default:
}
}
call like this
initializaMap(savedInstanceState);

it will not work because the navigation drawer takes a fragment and you are initializing :
fragment = new MapFragment();
so it takes the MapFragment default layout .
you must to change the updateDisplay to takes an activity not a fragment . In another words change the navigation drawer to activities instead of fragments

Related

How to get location in Fragment?

Hi im try to find location in fragment. but i cannot get location.
LocationManager locationmanager= (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); return null.how can i fix it
SocialFragment.java
public class SocialFragment 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.map);
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;
// 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));
LocationManager locationmanager= (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationmanager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
});
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();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
ArrayList country, city, districts;
StringBuffer stringBuffer = new StringBuffer();
String response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
try {
City();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}}
Please add logcat errors or result for more details. Meanwhile try this in your onMapready:
// enable location buttons
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// fetch last location if any from provider - GPS.
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc == null) {
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// getting location of user
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
// do something with Latlng
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
// do something
}
#Override
public void onProviderDisabled(String provider) {
// notify user "GPS or Network provider" not available
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 500, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
}
else {
// do something with last know location
}
Try by putting
LocationManager locationmanager= (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); outside of onMapReady

reposition a marker when I press button android API V2

I have the following code and, when I press a menu button I would like to reposition the same marker and the camera but I do not have idea how to do it, I've read oficial documentation but I haven't found info. I'm using repositionMarker() method to do it, but Im not sure what to do. Thanks
public class Init extends AppCompatActivity implements OnMapReadyCallback
{
private MapFragment map;
static final LatLng PERTH = new LatLng(19.0436, -98.1981);
private CameraUpdate camaraloc, camaraloczoom;
private Marker markerloc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio);
map = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (map != null)
{
map.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap map)
{
map.setMyLocationEnabled(true);
camaraloc = CameraUpdateFactory.newLatLng(PERTH);
camaraloczoom = CameraUpdateFactory.zoomTo(8);
map.moveCamera(camaraloc);
map.animateCamera(camaraloczoom);
markerloc = map.addMarker(new MarkerOptions().position(PERTH)
.title("city").snippet("esp").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_inicio, menu);
return true;
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.action_settings:
Toast.makeText(this, "name marker: "+markerloc.getTitle(), Toast.LENGTH_SHORT).show();
reposicionMarker();
return true;
}
return super.onOptionsItemSelected(item);
}
public void repositionMarker()
{
camaraloc = CameraUpdateFactory.newLatLng(new LatLng(16.65, -91.8658));
camaraloczoom = CameraUpdateFactory.zoomTo(15);
if ( markerloc != null )
markerloc.remove();
markerloc.setPosition(new LatLng(16.65, -91.8658));
// here is where I dont know what to do
}
}
Calling setLocation on the Marker should work, for changing its location. What seems to be your problem is that you are actually removing the marker right before you set the new location.

Using fragments from navigation drawer to overlay activity

I am having trouble laying a fragment on top of my existing activity. What I am attempting to accomplish is as follows: Open app -> mapView is created -> navigation drawer is created -> button on navigation drawer opens new fragment laying on top on mapView (while mapView not being visible). What is happening is the layout for the fragment is showing, but the white space of the layout is transparent and I am still able to use the map. Here is my code:
MainActivity.java
public class MainActivity extends Activity {
private MapView mapView;
private LocationListener locationListener;
private GeometryLayer locationLayer;
private Timer locationTimer;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setMap();
initDrawer(savedInstanceState);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SelectItem(position);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void SelectItem(int possition) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new ProfileFragment();
args.putString(ProfileFragment.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(ProfileFragment.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 1:
fragment = new ProfileFragment();
args.putString(ProfileFragment.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(ProfileFragment.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 4:
fragment = new SettingsFragment();
args.putString(SettingsFragment.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(SettingsFragment.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
default:
break;
}
fragment.setArguments(args);
android.app.FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onStart() {
super.onStart();
// 4. Start the map - mandatory.
mapView.startMapping();
// Create layer for location circle
locationLayer = new GeometryLayer(mapView.getLayers().getBaseProjection());
mapView.getComponents().layers.addLayer(locationLayer);
// add GPS My Location functionality
final MyLocationCircle locationCircle = new MyLocationCircle(locationLayer);
initGps(locationCircle);
// Run animation
locationTimer = new Timer();
locationTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
locationCircle.update(mapView.getZoom());
}
}, 0, 50);
}
#Override
protected void onStop() {
// Stop animation
locationTimer.cancel();
// Remove created layer
mapView.getComponents().layers.removeLayer(locationLayer);
// remove GPS support, otherwise we will leak memory
deinitGps();
// Note: it is recommended to move startMapping() call to onStart method and implement onStop method (call MapView.stopMapping() from onStop).
mapView.stopMapping();
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
protected void initGps(final MyLocationCircle locationCircle) {
final Projection proj = mapView.getLayers().getBaseLayer().getProjection();
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
locationCircle.setLocation(proj, location);
locationCircle.setVisible(true);
// recenter automatically to GPS point
// TODO in real app it can be annoying this way, add extra control that it is done only once
mapView.setFocusPoint(mapView.getLayers().getBaseProjection().fromWgs84(location.getLongitude(), location.getLatitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.debug("GPS onStatusChanged "+provider+" to "+status);
}
#Override
public void onProviderEnabled(String provider) {
Log.debug("GPS onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider) {
Log.debug("GPS onProviderDisabled");
}
};
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
for(String provider : providers){
locationManager.requestLocationUpdates(provider, 10000, 100, locationListener);
}
}
protected void deinitGps() {
// remove listeners from location manager - otherwise we will leak memory
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(locationListener);
}
// adjust zooming to DPI, so texts on rasters will be not too small
// useful for non-retina rasters, they would look like "digitally zoomed"
private void adjustMapDpi() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float dpi = metrics.densityDpi;
// following is equal to -log2(dpi / DEFAULT_DPI)
float adjustment = (float) - (Math.log(dpi / DisplayMetrics.DENSITY_HIGH) / Math.log(2));
Log.debug("adjust DPI = "+dpi+" as zoom adjustment = "+adjustment);
mapView.getOptions().setTileZoomLevelBias(adjustment / 2.0f);
}
private void addCartoDbLayer() {
// 5.1 Define styles for all possible geometry types
int color = Color.BLUE;
int minZoom = 5;
final Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.point);
final StyleSet<PointStyle> pointStyleSet = new StyleSet<PointStyle>();
PointStyle pointStyle = PointStyle.builder().setBitmap(pointMarker).setSize(0.05f).setColor(color).setPickingSize(0.2f).build();
pointStyleSet.setZoomStyle(minZoom, pointStyle);
final StyleSet<LineStyle> lineStyleSet = new StyleSet<LineStyle>();
LineStyle lineStyle = LineStyle.builder().setWidth(0.04f).setColor(Color.WHITE).build();
lineStyleSet.setZoomStyle(minZoom, lineStyle);
final StyleSet<PolygonStyle> polygonStyleSet = new StyleSet<PolygonStyle>(null);
PolygonStyle polygonStyle = PolygonStyle.builder().setColor(0xFFFF6600 & 0x80FFFFFF).setLineStyle(lineStyle).build();
polygonStyleSet.setZoomStyle(minZoom, polygonStyle);
String account = "bitciv";
String table = "units"; // kihelkonnad_1897, maakond_20120701
String columns = "cartodb_id,name,iso2,pop2005,area,the_geom_webmercator"; // NB! always include cartodb_id and the_geom_webmercator
//String columns = "cartodb_id,job,the_geom_webmercator";
int limit = 5000; // max number of objects
String sql = "SELECT "+columns+" FROM "+table+" WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT "+limit;
// String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads WHERE type in ('trunk','primary') AND the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
// String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
CartoDbDataSource cartoDataSource = new CartoDbDataSource(mapView.getLayers().getBaseLayer().getProjection(), account, sql) {
#Override
protected Label createLabel(Map<String, String> userData) {
StringBuffer labelTxt = new StringBuffer();
for (Map.Entry<String, String> entry : userData.entrySet()){
labelTxt.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
return new DefaultLabel("Data:", labelTxt.toString());
}
#Override
protected StyleSet<PointStyle> createPointStyleSet(Map<String, String> userData, int zoom) {
return pointStyleSet;
}
#Override
protected StyleSet<LineStyle> createLineStyleSet(Map<String, String> userData, int zoom) {
return lineStyleSet;
}
#Override
protected StyleSet<PolygonStyle> createPolygonStyleSet(Map<String, String> userData, int zoom) {
return polygonStyleSet;
}
};
GeometryLayer cartoLayerTrunk = new GeometryLayer(cartoDataSource);
mapView.getLayers().addLayer(cartoLayerTrunk);
}
private void setMap(){
// enable logging for troubleshooting - optional
Log.enableAll();
Log.setTag("hellomap");
// 1. Get the MapView from the Layout xml - mandatory
mapView = (MapView) findViewById(R.id.mapView);
// Optional, but very useful: restore map state during device rotation,
// it is saved in onRetainNonConfigurationInstance() below
Components retainObject = (Components) getLastNonConfigurationInstance();
if (retainObject != null) {
// just restore configuration and update listener, skip other initializations
mapView.setComponents(retainObject);
return;
} else {
// 2. create and set MapView components - mandatory
mapView.setComponents(new Components());
}
// 3. Define map layer for basemap - mandatory.
// Here we use MapQuest open tiles.
// We use online data source for the tiles and the URL is given as template. Almost all online tiled maps use EPSG3857 projection.
RasterDataSource dataSource = new HTTPRasterDataSource(new EPSG3857(), 0, 18, "http://otile1.mqcdn.com/tiles/1.0.0/osm/{zoom}/{x}/{y}.png");
RasterLayer mapLayer = new RasterLayer(dataSource, 0);
mapView.getLayers().setBaseLayer(mapLayer);
adjustMapDpi();
// Show performance indicator
//mapView.getOptions().setFPSIndicator(true);
// Increase raster tile download speed by doing 4 downloads in parallel
//mapView.getOptions().setRasterTaskPoolSize(4);
// set initial map view camera - optional. "World view" is default
// Location: San Francisco
// NB! it must be in base layer projection (EPSG3857), so we convert it from lat and long
mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-122.41666666667f, 37.76666666666f));
// rotation - 0 = north-up
mapView.setMapRotation(0f);
// zoom - 0 = world, like on most web maps
mapView.setZoom(16.0f);
// tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed is 30 degrees.
mapView.setTilt(65.0f);
// Activate some mapview options to make it smoother - optional
mapView.getOptions().setPreloading(true);
mapView.getOptions().setSeamlessHorizontalPan(true);
mapView.getOptions().setTileFading(true);
mapView.getOptions().setKineticPanning(true);
mapView.getOptions().setDoubleClickZoomIn(true);
mapView.getOptions().setDualClickZoomOut(true);
// set sky bitmap - optional, default - white
mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setSkyOffset(4.86f);
mapView.getOptions().setSkyBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.sky_small));
// Map background, visible if no map tiles loaded - optional, default - white
mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
mapView.getOptions().setBackgroundPlaneBitmap(
UnscaledBitmapLoader.decodeResource(getResources(),
R.drawable.background_plane));
mapView.getOptions().setClearColor(Color.WHITE);
// configure texture caching - optional, suggested
mapView.getOptions().setTextureMemoryCacheSize(40 * 1024 * 1024);
mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);
// define online map persistent caching - optional, suggested. Default - no caching
mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
// set persistent raster cache limit to 100MB
mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);
/* // 5. Add simple marker to map.
// define marker style (image, size, color)
Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker);
MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).setColor(Color.WHITE).build();
// define label what is shown when you click on marker
Label markerLabel = new DefaultLabel("San Francisco", "Here is a marker");
// define location of the marker, it must be converted to base map coordinate system
MapPos markerLocation = mapLayer.getProjection().fromWgs84(-122.416667f, 37.766667f);
// create layer and add object to the layer, finally add layer to the map.
// All overlay layers must be same projection as base layer, so we reuse it
MarkerLayer markerLayer = new MarkerLayer(mapLayer.getProjection());
markerLayer.add(new Marker(markerLocation, markerLabel, markerStyle, null));
mapView.getLayers().addLayer(markerLayer); */
// add event listener
MyMapEventListener mapListener = new MyMapEventListener(this, mapView);
mapView.getOptions().setMapListener(mapListener);
// 5. Add CartoDB vector layer to map
addCartoDbLayer();
}
private void initDrawer(Bundle savedInstanceState){
// Initializing
dataList = new ArrayList<DrawerItem>();
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerList.setBackgroundResource(R.color.white);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Profile", R.drawable.ic_action_email));
dataList.add(new DrawerItem("Messages", R.drawable.ic_action_good));
dataList.add(new DrawerItem("Statistics", R.drawable.ic_action_gamepad));
dataList.add(new DrawerItem("Settings", R.drawable.ic_action_labels));
dataList.add(new DrawerItem("Invite", R.drawable.ic_action_search));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(0);
}
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.nutiteq.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
If I understand correctly, what is happening is that the white spaces of your top most Fragment are not capturing click events. To solve this, you need to make the root ViewGroup of the top most Fragment clickable. If the secondFragmentto be added takes up the whole or most of the screen, it is better to call remove() instead of add() in your FragmentTransaction to avoid this issue completely.

duplicated id with fragment

I'm trying to applicate drawernavigation (my first fragment is a map & the others are just some fragments with simple layouts).So it runs fine & I can navigate between my fragments but when I return to the first fragment which is a map I got a crash
logcat:
11-20 11:03:27.306: E/AndroidRuntime(13787): FATAL EXCEPTION: main
11-20 11:03:27.306: E/AndroidRuntime(13787): android.view.InflateException: Binary XML file line #6: Error inflating class fragment
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
11-20 11:03:27.306: E/AndroidRuntime(13787): at challenge.arabe.taxitaxi.HomeFragment.onCreateView(HomeFragment.java:48)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:828)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1032)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.BackStackRecord.run(BackStackRecord.java:622)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1382)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:426)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.os.Handler.handleCallback(Handler.java:605)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.os.Handler.dispatchMessage(Handler.java:92)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.os.Looper.loop(Looper.java:137)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.ActivityThread.main(ActivityThread.java:4511)
11-20 11:03:27.306: E/AndroidRuntime(13787): at java.lang.reflect.Method.invokeNative(Native Method)
11-20 11:03:27.306: E/AndroidRuntime(13787): at java.lang.reflect.Method.invoke(Method.java:511)
11-20 11:03:27.306: E/AndroidRuntime(13787): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-20 11:03:27.306: E/AndroidRuntime(13787): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-20 11:03:27.306: E/AndroidRuntime(13787): at dalvik.system.NativeStart.main(Native Method)
11-20 11:03:27.306: E/AndroidRuntime(13787): Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f05000c, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.app.Activity.onCreateView(Activity.java:4253)
11-20 11:03:27.306: E/AndroidRuntime(13787): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:673)
11-20 11:03:27.306: E/AndroidRuntime(13787): ... 18 more
I think this the most impportant:
Duplicate id 0x7f05000c, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment
so this is my code:
LoginScreen:a fragmentActivity which make all call for the fragment
public class LoginScreen extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
MapFragment mMap;
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(status == ConnectionResult.SUCCESS) {
// what you want to do
Toast.makeText(getApplicationContext(), "good connection", Toast.LENGTH_SHORT).show();
}
// setUpMapIfNeeded();
// addTwitterMarq();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
//getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void addTwitterMarq() {
// TODO Auto-generated method stub
LatLng pos = new LatLng(48.85078, 2.34440);
googleMap.addMarker(new MarkerOptions()
.title("Twitter")
.snippet("Twitter HQ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(pos)
);
}
private void setUpMapIfNeeded() {
// TODO Auto-generated method stub
if (googleMap == null) {
// Try to obtain the map from the SupportMapFragment.
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
googleMap.setMyLocationEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (googleMap != null) {
// setUpMap();
drawTestJunk();
}
}
}
private void drawTestJunk() {
// TODO Auto-generated method stub
UiSettings settings = googleMap.getUiSettings();
settings.setZoomControlsEnabled(true);
settings.setCompassEnabled(true);
settings.setTiltGesturesEnabled(false);
settings.setMyLocationButtonEnabled(true);
CameraUpdate camUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(45.53, -73.59), 14);
googleMap.moveCamera(camUpdate);
/**
* "Markers" lesson
*/
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(45.538490,-73.598480))
.title("Hello world")
.snippet("what does a snippet look like?")
.draggable(true)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
);
/**
* skipping other "Marker" lessons, to move on to Lines, Polygons, and Circles.
* Topic list for later study:
* - Customized info windows
* - Marker click events
* - Marker drag events
* - Info window click events
*/
/**
* "Lines, Polygons, and Circles" lesson
*/
// LINE
PolylineOptions route = new PolylineOptions()
.add(new LatLng(45.538451240403596, -73.59851807077722) )
.add(new LatLng(45.5390432, -73.5997465) )
.add(new LatLng(45.5387234, -73.6000517) )
.add(new LatLng(45.5389376, -73.6005275) )
.color(Color.GREEN)
;
Polyline polyline = googleMap.addPolyline(route);
//you can also call PolylineOptions.addAll(Iterable<LatLng>) if the points are already in a list
// POLYGON
ArrayList<LatLng> hole= new ArrayList<LatLng>();
hole.add(new LatLng(45.5275, -73.5925));
hole.add(new LatLng(45.5225, -73.5925));
hole.add(new LatLng(45.5225, -73.5975));
hole.add(new LatLng(45.5275, -73.5975));
PolygonOptions rectOptions = new PolygonOptions()
.add(new LatLng(45.53, -73.59),
new LatLng(45.52, -73.59),
new LatLng(45.52, -73.60),
new LatLng(45.53, -73.60),
new LatLng(45.53, -73.59))
.addHole(hole)
.strokeColor(Color.RED)
.fillColor(Color.BLUE);
Polygon polygon = googleMap.addPolygon(rectOptions);
// And sure, why not, a CIRCLE
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(45.525, -73.595))
.radius(100);
Circle circle = googleMap.addCircle(circleOptions);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_screen, menu);
return true;
}
}
and this is my main layout for the fragmentActivity:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!--
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
-->
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
and this is the xml layout of the mapfragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment"/>
</RelativeLayout>
and this is the mapfragment code:
public class HomeFragment extends Fragment {
int mCurrentPosition = -1;
MapFragment mMap;
GoogleMap googleMap;
final static String ARG_POSITION = "position";
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mCurrentPosition = savedInstanceState.getInt(ARG_POSITION);
}
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
// int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
// if(status == ConnectionResult.SUCCESS) {
// // what you want to do
// //Toast.makeText(getApplicationContext(), "good connection", Toast.LENGTH_SHORT).show();
// }
setUpMapIfNeeded();
addTwitterMarq();
return rootView;
}
private void addTwitterMarq() {
// TODO Auto-generated method stub
LatLng pos = new LatLng(48.85078, 2.34440);
googleMap.addMarker(new MarkerOptions()
.title("Twitter")
.snippet("Twitter HQ")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.position(pos)
);
}
private void setUpMapIfNeeded() {
// TODO Auto-generated method stub
if (googleMap == null) {
// Try to obtain the map from the SupportMapFragment.
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
googleMap.setMyLocationEnabled(true);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (googleMap != null) {
// setUpMap();
drawTestJunk();
}
}
}
private void drawTestJunk() {
// TODO Auto-generated method stub
UiSettings settings = googleMap.getUiSettings();
settings.setZoomControlsEnabled(true);
settings.setCompassEnabled(true);
settings.setTiltGesturesEnabled(false);
settings.setMyLocationButtonEnabled(true);
CameraUpdate camUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(45.53, -73.59), 14);
googleMap.moveCamera(camUpdate);
/**
* "Markers" lesson
*/
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(45.538490,-73.598480))
.title("Hello world")
.snippet("what does a snippet look like?")
.draggable(true)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
);
/**
* skipping other "Marker" lessons, to move on to Lines, Polygons, and Circles.
* Topic list for later study:
* - Customized info windows
* - Marker click events
* - Marker drag events
* - Info window click events
*/
/**
* "Lines, Polygons, and Circles" lesson
*/
// LINE
PolylineOptions route = new PolylineOptions()
.add(new LatLng(45.538451240403596, -73.59851807077722) )
.add(new LatLng(45.5390432, -73.5997465) )
.add(new LatLng(45.5387234, -73.6000517) )
.add(new LatLng(45.5389376, -73.6005275) )
.color(Color.GREEN)
;
Polyline polyline = googleMap.addPolyline(route);
//you can also call PolylineOptions.addAll(Iterable<LatLng>) if the points are already in a list
// POLYGON
ArrayList<LatLng> hole= new ArrayList<LatLng>();
hole.add(new LatLng(45.5275, -73.5925));
hole.add(new LatLng(45.5225, -73.5925));
hole.add(new LatLng(45.5225, -73.5975));
hole.add(new LatLng(45.5275, -73.5975));
PolygonOptions rectOptions = new PolygonOptions()
.add(new LatLng(45.53, -73.59),
new LatLng(45.52, -73.59),
new LatLng(45.52, -73.60),
new LatLng(45.53, -73.60),
new LatLng(45.53, -73.59))
.addHole(hole)
.strokeColor(Color.RED)
.fillColor(Color.BLUE);
Polygon polygon = googleMap.addPolygon(rectOptions);
// And sure, why not, a CIRCLE
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(45.525, -73.595))
.radius(100);
Circle circle = googleMap.addCircle(circleOptions);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//setUpMapIfNeeded();
//addTwitterMarq();
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putInt(ARG_POSITION, mCurrentPosition);
}
public void updateArticleView(int position) {
mCurrentPosition = position;
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Bundle args = getArguments();
if (args != null) {
// Set article based on argument passed in
updateArticleView(args.getInt(ARG_POSITION));
} else if (mCurrentPosition != -1) {
// Set article based on saved instance state defined during onCreateView
updateArticleView(mCurrentPosition);
}
}
}
I think that the problem is located in onResume & onCreateView methods!!
Hope that you'll help me
thanks.
use this
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
/>
and override method onDestroyView() and Just put this code in onDestroyView()
public void onDestroyView()
{
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
Try to reuse/recycle your layout.
I am running into "duplicate id" when using a map fragment.
So in onCreateView instead of
final View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
i am using
public class YourFragment extends Fragment {
public YourFragment(){}
...
private static View rootView;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
I think you have to try to retrieve old Fragments instance instead of recreating it each time a drawer item is selected. In your displayView method of LoginScreen Activity, you have to do something like that in the switch:
Fragment fragment = null;
String title = getResources().getString(SOME_FRAGMENT_TITLE);
switch (position) {
case 1:
fragment = (YourFragment) fm.findFragmentByTag(title);
if (fragment == null) fragment = new YourFragment();
break;
}

how to show map of specific city in google map when app start

below is my code which display map of all world i want when application start is show specific city not world map i follow this tutorial http://android-er.blogspot.com/2013/01/google-maps-android-api-v2-example-draw.html every thing work fine but i want when app start first time is display specific city map not all global map i dont want show globap map like this image http://1.bp.blogspot.com/-dwjqTWCdONg/UObUk1syAFI/AAAAAAAAGy8/S43YMKuXZRc/s1600/screen_MapsAPIv2_Polygon.png on app start i want specific city map like newyork for example.
public class MainActivity extends Activity
implements OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
TextView tvLocInfo;
boolean markerClicked;
PolygonOptions polygonOptions;
Polygon polygon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
FragmentManager myFragmentManager = getFragmentManager();
MapFragment myMapFragment
= (MapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onMapClick(LatLng point) {
tvLocInfo.setText(point.toString());
myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
markerClicked = false;
}
#Override
public void onMapLongClick(LatLng point) {
tvLocInfo.setText("New marker added#" + point.toString());
myMap.addMarker(new
MarkerOptions().position(point).title(point.toString()));
markerClicked = false;
}
#Override
public boolean onMarkerClick(Marker marker) {
if(markerClicked){
if(polygon != null){
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(Color.RED);
polygonOptions.fillColor(Color.BLUE);
polygon = myMap.addPolygon(polygonOptions);
}else{
if(polygon != null){
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
}
return true;
}
}
add this code to your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
// define point to center on
LatLng origin = new LatLng(40.67, -73.94);
CameraUpdate panToOrigin = CameraUpdateFactory.newLatLng(origin);
myMap.moveCamera(panToOrigin);
// set zoom level with animation
myMap.animateCamera(CameraUpdateFactory.zoomTo(14), 400, null);
}
After the onClikListener are setted (into onCreate), put this code
LatLng NewYork= new LatLng(40.714623,-74.006605);
CameraPosition camPos = new CameraPosition.Builder().target(NewYork).zoom(14).build();
CameraUpdate cam = CameraUpdateFactory.newCameraPosition(camPos);
myMap.animateCamera(cam);
It will animate your map and move the camera to NY

Categories

Resources