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;
}
Related
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
I have completed the google maps and slide menu individually.
I can not combine both into one.
Because google maps extends FragmentActivity.
For slide menu i have to use Fragement.
I try to convert the FragmetActivity to Fragment.
But i come to know that that is not possible.
I can not get any example for google map with slide menu.
Any one can provide me a example or link for google map with slide menu.
Please help me resolve my problem.
Here i attached my SlideActivity.java
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
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>();
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer,
R.string.app_name,
R.string.app_name
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
displayView(0);
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
// fragment = new MainActivity();
/*
Intent i = new Intent(getApplicationContext(),MainActivity.class); startActivity(i);
*/
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
My Map.java:
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleMap googleMap;
googleMap = ((SupportMapFragment)(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
LatLng latLng = new LatLng(-33.796923, 150.922433);
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("My Spot")
.snippet("This is my spot!")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
Thanks for the answers.. Finally i found the solution from this
link....
Final Solutions is:
public class MainActivityNew extends Fragment{
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_location_info, container,
false);
mMapView = (MapView) v.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();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#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();
}
}
fragment_location_info.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I have been reading every possible threads on stackoverflow for the past two days, and I can't figure out where my issue is... Experiencing a new error every time I bring a "fix"
Before the code, the end state: I'm trying to have a navigation drawer between multiple fragments. One of them is a restaurant search that display search results in a SupportMapFragment.
I don't get errors when I first load my fragment that contains the map, but I get error when I switch to another fragment thanks to NavigationDrawer, and I get an error when I'm pressing the back button, plus many other goodies.
Here is my code:
NavigationDrawer.java
public class NavigationDrawerActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mListFragments;
public static FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
mTitle = mDrawerTitle = getTitle();
mListFragments = new String[] {"Search","Feed","About","Test"};
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mListFragments));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
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);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.navigation_drawer, menu);
return super.onCreateOptionsMenu(menu);
}
#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;
}
// Handle action buttons
switch(item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
public void Logout(MenuItem item) {
SharedPreferences settings = getSharedPreferences(App.PREFS_NAME, 0);
settings.edit().remove("email").apply();
settings.edit().remove("password").apply();
settings.edit().remove("userID").apply();
settings.edit().putBoolean("hasLoggedIn",false).apply();
Intent intent = new Intent(this,LoginActivity.class);
startActivity(intent);
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
Fragment fragment;
private void selectItem(int position) {
// update the main content by replacing fragments
switch (position){
// Search engine
// case 0:
// if ( fragment!=null) fragment.onDestroy();
// fragment = new RestaurantSearchFragment();
// break;
// Rating feed
case 1:
// fragment = new RatingFeedTabHostFragment();
// break;
// About screen
case 2:
fragment = new AboutFragment();
break;
case 3:
fragment = new RestaurantSearchFragment2();
break;
default:
fragment = new AboutFragment();
break;
}
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mListFragments[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
}
fragment_restaurant_search.xml
<!-- Your layouts-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!--The content you want to add-->
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_search_dark"
android:layout_gravity="center"
android:id="#+id/icon_search"/>
<AutoCompleteTextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:hint="Enter Restaurant Name"
android:id="#+id/restaurant_search"
android:completionThreshold="1"
android:imeOptions="actionSearch"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button_search"
android:text="Go!"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_location_found"
android:id="#+id/location_search_image"
android:layout_gravity="center"
/>
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Near Current Location"
android:singleLine="true"
android:imeOptions="actionSearch"
android:id="#+id/location_search"
android:inputType="none"/>
</LinearLayout>
<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="200dp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
<fragment android:name="com.bestpick.bestpickapplication.Screens.NavigationDrawer.RestaurantSearch.RestaurantsListFragment"
android:id="#+id/restaurant_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_restaurants"
/>
</LinearLayout>
RestaurantSearchFragment2.java
public class RestaurantSearchFragment2 extends Fragment
{
// Handles to UI widgets
private EditText locationSearchText;
private AutoCompleteTextView restaurantSearch;
private FragmentActivity context;
// sets context from calling Navigation Drawer Activity (FragmentActivity)
#Override
public void onAttach(Activity activity) {
context=(FragmentActivity) activity;
super.onAttach(activity);
}
public static FragmentManager fragmentManager;
private RestaurantMapFragment restaurantMapFragment;
private RestaurantsListFragment restaurantsListFragment;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_restaurant_search, container, false);
fragmentManager = getChildFragmentManager();
// setting up the restaurant list fragment
restaurantsListFragment = (RestaurantsListFragment) fragmentManager.findFragmentById(R.id.restaurant_fragment);
if (restaurantsListFragment == null) {
restaurantsListFragment = new RestaurantsListFragment();
fragmentManager.beginTransaction().replace(R.id.restaurant_fragment, restaurantsListFragment).commit();
}
// setting up the restaurant map fragment
restaurantMapFragment = (RestaurantMapFragment) fragmentManager.findFragmentById(R.id.map);
if (restaurantMapFragment==null){
restaurantMapFragment = new RestaurantMapFragment();
fragmentManager.beginTransaction().replace(R.id.map,restaurantMapFragment).commit();
}
return view;
}
}
RestaurantFragmentMap.java
public class RestaurantMapFragment extends Fragment {
private static View view;
/**
* Note that this may be null if the Google Play services APK is not
* available.
*/
private static GoogleMap mMap;
private static Double latitude, longitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
view = (RelativeLayout) inflater.inflate(R.layout.location_fragment, container, false);
// Passing harcoded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map
latitude = 26.78;
longitude = 72.56;
setUpMapIfNeeded(); // For setting up the MapFragment
return view;
}
/***** Sets up the map if it is possible to do so *****/
public static 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) NavigationDrawerActivity.fragmentManager
.findFragmentById(R.id.location_map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
setUpMap();
}
}
/**
* This is where we can add markers or lines, add listeners or move the
* camera.
* <p>
* This should only be called once and when we are sure that {#link #mMap}
* is not null.
*/
private static void setUpMap() {
// For showing a move to my loction button
mMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"));
// For zooming automatically to the Dropped PIN Location
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
if (mMap != null)
setUpMap();
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) NavigationDrawerActivity.fragmentManager
.findFragmentById(R.id.location_map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
setUpMap();
}
}
#Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**** The mapfragment's id must be removed from the FragmentManager
**** or else if the same it is passed on the next time then
**** app will crash ****/
#Override
public void onDestroyView() {
super.onDestroyView();
if (mMap != null) {
RestaurantSearchFragment2.fragmentManager.beginTransaction()
.remove(RestaurantSearchFragment2.fragmentManager.findFragmentById(R.id.location_map)).commitAllowingStateLoss();
mMap = null;
}
}
}
location_fragment.xml
<?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/location_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
I have had all the errors in the world, the most fancy that I have right now is:
10-15 23:39:45.786 6568-6568/com.bestpick.bestpickapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bestpick.bestpickapplication, PID: 6568
java.lang.NullPointerException
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:651)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:1937)
at android.support.v4.app.Fragment.performDestroy(Fragment.java:1721)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1071)
at android.support.v4.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1218)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:639)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:450)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
and:
10-15 23:34:54.866 6251-6251/com.bestpick.bestpickapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.bestpick.bestpickapplication, PID: 6251
java.lang.RuntimeException: Unable to destroy activity {com.bestpick.bestpickapplication/com.bestpick.bestpickapplication.Screens.NavigationDrawer.NavigationDrawerActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3497)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3515)
at android.app.ActivityThread.access$1400(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1249)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1360)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1378)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
at com.bestpick.bestpickapplication.Screens.NavigationDrawer.RestaurantSearch.RestaurantMapFragment.onDestroyView(RestaurantMapFragment.java:120)
at android.support.v4.app.Fragment.performDestroyView(Fragment.java:1709)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1011)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1103)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroyView(FragmentManager.java:1932)
at android.support.v4.app.Fragment.performDestroyView(Fragment.java:1706)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1011)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1103)
at android.support.v4.app.FragmentManagerImpl.dispatchDestroy(FragmentManager.java:1938)
at android.support.v4.app.FragmentActivity.onDestroy(FragmentActivity.java:336)
at android.app.Activity.performDestroy(Activity.java:5403)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1117)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3484)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3515)
at android.app.ActivityThread.access$1400(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1249)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I googled them all, read blogs, stackoverflow... still can't figure out anything!
Thanks for your much appreciated help
Do this for backpress....
#Override
public void onBackPressed(){
android.support.v4.app.FragmentManager fm = this.getSupportFragmentManager();
if(fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
else {
}
}
I am integrating Navigation drawer menu with Google Map fragement. I have a mapactivity it show the directions path from my start & destination value given in screen1. My mapactivity is showing the directions but while switching to another item in navigation menu my application doesn't shows up the next fragment.give me suggestions about map My MapActivity file as shown in below
public class MapActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private SlidingUpPanelLayout slidingUpPanelLayout;
// 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;
private int historyPosition;
SharedPreferences sharedpreferences;
//Map Items
LocationManager locManager;
Drawable drawable;
Document document;
GMapV2GetRouteDirection v2GetRouteDirection;
MarkerOptions markerOptions;
Location location ;
private SupportMapFragment fragment;
//Map Items
List<Overlay> mapOverlays;
// Google Map
private GoogleMap mGoogleMap;
String value;
public static LatLng SOURCE = new LatLng(0,0);
public static LatLng DESTINATION= new LatLng(0,0);
double longitude;
double latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
value = getIntent().getStringExtra("KEY");
setContentView(R.layout.activity_map);
//Textview intialization
distancetextView=(TextView)findViewById(R.id.name11);
currentSpeedTextView=(TextView)findViewById(R.id.textView2);
estimatedDistance=(TextView)findViewById(R.id.textView1);
estimatedTime=(TextView)findViewById(R.id.textView3);
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);
slidingUpPanelLayout=(SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().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
) {
#Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
//Geo Coder
Geocoder coder = new Geocoder(this);
try {
ArrayList<Address> adresses = (ArrayList<Address>) coder.getFromLocationName(value, 50);
for(Address add : adresses){
if (adresses.size()>0) {//Controls to ensure it is right address such as country etc.
longitude = add.getLongitude();
latitude = add.getLatitude();
}
}
} catch (IOException e) {
e.printStackTrace();
}
DESTINATION=new LatLng(latitude,longitude);
// check if GPS enabled
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation())
{
double Curr_Latitude = gpsTracker.latitude;
double Curr_Longitude =gpsTracker.longitude;
SOURCE=new LatLng(Curr_Latitude,Curr_Longitude);
}
v2GetRouteDirection = new GMapV2GetRouteDirection();
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mGoogleMap = supportMapFragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
mGoogleMap.setTrafficEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
markerOptions = new MarkerOptions();
GetRouteTask getRoute = new GetRouteTask();
getRoute.execute();
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.drawer_layout, new PlaceholderFragment()).commit();
}
}
}
*/
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
*
* #author VIJAYAKUMAR M
* This class Get Route on the map
*
*/
private class GetRouteTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response = "";
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(MapActivity.this);
Dialog.setMessage("Loading route...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
//Get All Route values
document = v2GetRouteDirection.getDocument(SOURCE, DESTINATION, GMapV2GetRouteDirection.MODE_DRIVING);
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
mGoogleMap.clear();
if(response.equalsIgnoreCase("Success")){
ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(5).color(
Color.BLUE);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
mGoogleMap.addPolyline(rectLine);
markerOptions.position(DESTINATION);
markerOptions.draggable(true);
mGoogleMap.addMarker(markerOptions);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(SOURCE,
7));
String text=v2GetRouteDirection.getTotalDistance(document);
distancetextView.setText(text);
MapActivity.estimatedDistance.setText("DISTANCE TRAVELLED "+"0 KM");
String text1=v2GetRouteDirection.getTotalDuration(document);
estimatedTime.setText("ESTIMATED TIME "+text1);
}
Dialog.dismiss();
}
}
#Override
protected void onStop() {
super.onStop();
finish();
}
/**
* 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
System.out.println("--ON SLIDE CLICKED----");
sharedpreferences = getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
historyPosition=sharedpreferences.getInt("historyposition", 0);
Editor editor = sharedpreferences.edit();
editor.putInt("historyposition", position);
editor.commit();
System.out.println("----The Position at which the pointer Picked--"+position);
System.out.println("----The Position at which the Prev pointer Picked--"+historyPosition);
if(historyPosition!=position){
displayView(position);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, 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.
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 = getSupportFragmentManager();
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;
getSupportActionBar().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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container,
false);
return rootView;
}
}
}
My map_layout file
<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" />
<com.vysystems.travelgo.slidinguppanel.SlidingUpPanelLayout
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eeeeee"
android:orientation="vertical"
android:clickable="true"
android:focusable="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:orientation="horizontal">
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="14sp"
android:gravity="center_vertical"
android:text="TOTAL DISTANCE "
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/name11"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="14sp"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="24dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="24dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="23dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
</LinearLayout>
</com.vysystems.travelgo.slidinguppanel.SlidingUpPanelLayout>
<!-- 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>
Tabs should be placed along the top of an app, below the action bar - as stated in the android design guidelines.
Please spend some time looking at these guidelines for tabs here (and the rest of the guidelines), they're essential for developing android apps!
Im new to the ActionBarCompat library.I want to develop an app which contains multiple fragments. Here is what i want to do
1.How to open a fragment when user select that from Navigation Drawer.
2.How to set a startup fragment which displays startup layout (example- In Google plus app,first its displays news feeds.when we select profile item from the side menu,then its hide the side menu/Navigation drawer and displays the profile layout)
Currently i have side menu and one fragment.
Here is the tutorial that i used to follow- wptrafficanalyzer
If you are going to use a slide out menu I recommend you use this slidemenu library I use it in my applications and it allows you to place whatever you want in the slide out menu, the menu is just a frame layout and you can put whatever you want in it (Listview, GridView, or even just a picture)
I am assuming by side menu you meant Navigation Drawer. You can find an answer in the below link.
Navigation Drawer with backword compatibility android
Do read
http://developer.android.com/design/patterns/navigation-drawer.html
Fragment is hosted by a Activity. So you need a container in the activity layout.
<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 // container to which you add or replace fragments
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"/>
</android.support.v4.widget.DrawerLayout>
Initially you don't click any item. So initially add fragment1 to the container.
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment1= new Fragment1();
fragTran.add(R.id.content_frame, fragment1);
fragTran.commit();
On click of listitem based on the position
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
Fragment fragment3= new Fragment3();
fragTran.replace(R.id.content_frame, fragment3);
fragTran.commit();
Hi check this code
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
DrawerLayout options_drawer;
FrameLayout main_frame;
ListView slider_list;
ActionBar action;
ActionBarDrawerToggle toggler;
BluetoothAdapter blue_adapter;
String options[] = { "Chat", "Device List", "Settings", "Emojis",
"Terms&Conditions" };
Fragment f;
private static final int REQUEST_ENABLE_BT = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// setSupportProgressBarIndeterminateVisibility(true);
action = getSupportActionBar();
action.setHomeButtonEnabled(true);
action.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
options_drawer = (DrawerLayout) findViewById(R.id.drawer);
main_frame = (FrameLayout) findViewById(R.id.main_frame);
slider_list = (ListView) findViewById(R.id.slider_list);
blue_adapter = BluetoothAdapter.getDefaultAdapter();
if (blue_adapter == null) {
Toast.makeText(getApplicationContext(),
"NO BLUETOOTH DEVICE FOUND", Toast.LENGTH_LONG).show();
finish();
}
ArrayAdapter<String> al = new ArrayAdapter<String>(
getApplicationContext(), R.layout.option_text, options);
slider_list.setAdapter(al);
slider_list.setOnItemClickListener(this);
/*
* toggler=new ActionBarDrawerToggle(MainActivity.this,
* options_drawer,R.
* drawable.ic_launcher,R.string.app_name,R.string.app_name){
*
* #Override public void onDrawerOpened(View drawerView) { // TODO
* Auto-generated method stub super.onDrawerOpened(drawerView);
* options_drawer.openDrawer(slider_list); }
*
* };
*/
// options_drawer.setDrawerListener(toggler);
if (savedInstanceState == null) {
f = new chat_fragment();
fragmentTransition(f);
}
}
#Override
public void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!blue_adapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == android.R.id.home) {
// If the drawer is open, close it; vice versa
if (options_drawer.isDrawerOpen(slider_list)) {
options_drawer.closeDrawer(slider_list);
} else {
options_drawer.openDrawer(slider_list);
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
options_drawer.closeDrawer(slider_list);
switch (position) {
case 0:
f = new chat_fragment();
fragmentTransition(f);
break;
case 1:
f = new device_list_fragment();
fragmentTransition(f);
break;
}
}
private void fragmentTransition(Fragment f2) {
// TODO Auto-generated method stub
FragmentTransaction fx = getSupportFragmentManager().beginTransaction();
fx.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fx.replace(R.id.main_frame, f2).commit();
}
}
And XML file is
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/main_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<ListView
android:id="#+id/slider_list"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff" >
</ListView>
try this link
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
android actionbarcompat is supported library for below android versions.In this you should do some modifications in code.I am giving some sample code with supported library
code:
public class SliderScreen extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
int checkboxValue=0;
// nav drawer title
private CharSequence mDrawerTitle;
private int selectedPosition=0;
private int currentpos=0;
// used to store app title
private CharSequence mTitle;
ProgressDialog progress_dialog;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
public static String letter = "";
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
ActionBarActivity activity;
MDatabase mdatabaseHelper;
String contact_id = "";
Cursor contactsCursor = null, databaseCursor = null,
messageDatabaseCursor = null,imageDatabaseCursor=null;
String contactCursorValue = "0";
int contactCursorRead = 0, messageCursorRead = 0,imageCursorRead=0;
int messageProgressValue = 0, contactProgressValue = 0,imageProgressValue=0;
AlertDialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_screen);
mTitle = mDrawerTitle = getTitle();
// activity=(ActionBarActivity) Context.getApplicationContext();
// 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);
progress_dialog = new ProgressDialog(SliderScreen.this);
progress_dialog.setMessage("please wait ");
Builder build=new Builder(SliderScreen.this);
build.setTitle("");
build.setMessage("Do you want to signout ? ");
build.setPositiveButton("Yes",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
build.setNegativeButton("No",new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
d=build.create();
// Database retrieval
mdatabaseHelper = new MDatabase(SliderScreen.this, null, null, 1);
mdatabaseHelper.getWritableDatabase();
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), true, 0));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1), true, 0));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1), true,0));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1), true, getMusicFilesCount()));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(5, -1)));
// What's hot, We will add a counter here
// 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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.listbulletes, // nav menu toggle icon
0, // nav drawer open - description for accessibility
0 // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
if(currentpos!=selectedPosition)
{
currentpos=selectedPosition;
displayView(selectedPosition);
}
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
// ActivityCompat.invalidateOptionsMenu(getParent());
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if(currentpos!=position)
{
Fragment fragment=new DefaultFragment();
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(" ");
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
selectedPosition=position;
mDrawerLayout.closeDrawer(mDrawerList);
/*
// display view for selected nav drawer item
if(selectedPosition==position)
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
displayView(position);
selectedPosition=position;
}
*/}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, 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(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 ContactsFragment();
break;
case 2:
fragment = new MessagesFragment();
break;
case 3:
fragment = new ImageFragment();
break;
case 4:
fragment = new MusicFragment();
break;
case 5:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
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");
}
}
private void showProgressDialog() {
progress_dialog.show();
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().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);
}
}