Navigation drawer hanged for 2 seconds while selecting one option - android

I have a navigation drawer in which i have many fragments which come on selecting any item of navigation drawer. On one item I am showing a map. I don't know why on selecting that item navigation drawer hangs for 2-3 seconds and then drawer close. I want it smooth like other items in navigation drawer.
Here is my code for navigation drawer in MainActivity:
private void displayView(int position) {
// update the main content by replacing fragments
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");
}
}
And here is the code of fragment on which the drawer hangs:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);
mPlaceType = getResources().getStringArray(R.array.place_type);
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) rootView.findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) rootView.findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
dialog.show();
}else {
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager =
(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
return rootView;
}

I also faced problem like that.
That totally work for me. Hope will help you
In your code,
In displayView function, put all codes in Runnable.
mPendingThread = new Runnable() {
#Override
public void run() {
//Here is all your code
switch(position){
.........
.........
}
};
In onCreate method,
mHandler = new Handler();
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
#Override
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
if (mPendingThread != null) {
mHandler.post(mPendingThread);
mPendingThread = null;
}
}
/** Called when a drawer is opened */
#Override
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);

Related

how to get progress circle before loading fragment on click of item in the navigation drawer

I have a navigation drawer in my app.On the click of an item from the navigation drawer particular fragment gets loaded.
but loading of a fragment is taking time of few seconds. i want a progress spinner to display in between so that it does not look like it got stuck.
i tried for using asynchronous task but it did not work because loading fragment from drawer does not include any background process.
Please suggest me something.
Navigation Drawer Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_navigation_fragments);
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.test_nav_tool);
setSupportActionBar(toolbar);
SharedPreferences w = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor share = w.edit();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
////if user skip-logout button in nav drawer will disable.
loggedIn=(w.getBoolean("loggedIn", loggedIn));
if(loggedIn==false){
nvDrawer.getMenu().findItem(R.id.logout).setVisible(false);
}
String user_name = (w.getString("name", user));
String type = "b";
type=(w.getString("type", type));
if(user_name.equalsIgnoreCase("name"))
user_name="Guest User";
if(type.equalsIgnoreCase("b")){
nvDrawer.getMenu().findItem(R.id.add_kitchen).setVisible(false);
nvDrawer.getMenu().findItem(R.id.nav_slideshow).setVisible(false);
}
header = LayoutInflater.from(this).inflate(R.layout.test_header_xml, null);
nvDrawer.addHeaderView(header);
TextView tv1=(TextView)header.findViewById(R.id.upload_image);
tv1.setText(user_name);
setupDrawerContent(nvDrawer);
drawerToggle=setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
if (savedInstanceState == null) {
nvDrawer.getMenu().performIdentifierAction(R.id.nav_camera, 0);
}
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(TestNavigationFragments.this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
setTitle(menuItem.getTitle());
switch(menuItem.getItemId()) {
case R.id.nav_camera:
fragment=new TESTfragNEIBMAP();
break;
case R.id.nav_share:
fragment = new TestFragACCOUNT();
break;
case R.id.nav_send:
fragment = new TESTfragSUPPORT();
break;
case R.id.add_kitchen:
fragment = new TestfragSELLER();
break;
case R.id.nav_slideshow:
fragment=new TestAddKitchenHistory();
break;
case R.id.nav_gallery:
fragment=new TestNavOrder();
break;
case R.id.logout:
try {
SharedPreferences s = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = s.edit();
editor.clear().commit();
Intent intent = new Intent(this, Login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
break;
}catch (Exception e){
Intent intent = new Intent(this, Login.class);
startActivity(intent);
}
case R.id.nav_track:
fragment = new TestTrack();
break;
}
if(fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
UPDATE
I have also tried writing progess code in drawer activity and dismiss it in Fragment onViewCreated() method...but i did not see any progress spinner at the time when i click on item of drawer because map is opened and it called its onViewCreated method very fast.
the other option can be adding splash screen on click of item in drawer till map will load but i don't have idea how to do it like how to finish splash screen when the map will become properly visible.
ProgressDialog progress; // Global varibale
// Initiate it in `OnCreateView()`
progress = ProgressDialog.show(getActivity(), "dialog title",
"dialog message", true);
//When Loaded data
progress.dismiss();
i got the issue resolved by closing the drawer before loading the fragments using handler class and set the progress dialog code in onClick of navigation drawer item.

ActionBarDrawerToggle disappears when addToBackStack(null) is used

In the selectItem() method, adding .addToBackStack(null) to my transaction seems to break the toggle button (the one that brings out the nav drawer when tapped). It just disappears entirely when a fragment is loaded (by clicking on the corresponding item in the nav drawer). If I comment out that line, the toggle button remains and works perfectly fine.
I need to call addToBackStack because I want back button functionality to work for those fragments, though. Why is it causing this issue?
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Log.d(TAG, "Item " + position + " selected");
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on position
Fragment aboutFragment = new AboutFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
Log.d(TAG, "selectItem() with position " + position);
switch(position) {
case 0:
fragmentManager.beginTransaction()
.replace(R.id.contributionsFragmentContainer, contributionsList)
//.addToBackStack(null)
.commit();
Log.d(TAG, "contributionsListFragment committed");
break;
case 1:
fragmentManager.beginTransaction()
.replace(R.id.contributionsFragmentContainer, aboutFragment)
//.addToBackStack(null)
.commit();
Log.d(TAG, "aboutFragment committed");
break;
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(itemArray[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
if (title != null && getActionBar() != null) {
getActionBar().setTitle(title);
}
}
private void addDrawerItems() {
itemArray = new String[] {"Home", "About", "Nearby", "Settings", "Feedback"};
Log.d(TAG, "Adding to itemArray");
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.title_activity_contributions);
setContentView(R.layout.activity_contributions);
Log.d("ContributionsActivity", "onCreate()");
// Activity can call methods in the fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById()
contributionsList = (ContributionsListFragment) getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment);
//Set up navigation drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
addDrawerItems();
setupDrawer();
...
}

Custom navigation drawer with activity & fragment

This is the code of the main activity, that contains a lateral menu with three button, what that i want to do is :
Modify this code and replace the action in the "listener" of the buttons in lateral menu, now when i press a button, a new fragment is created, but i want create a new activity (NOT a fragment), maintaining the layout (lateral menu).
How i can do this ?
public class MainActivity extends Activity {
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Create");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_refresh, "Read");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Help");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#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) {
// 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 super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CreateFragment();
break;
case 1:
fragment = new ReadFragment();
break;
case 2:
fragment = new HelpFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[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);
}
}
*********** EDIT 1 ***********
I try this method:
I replace this part :
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new CreateFragment();
break;
case 1:
fragment = new ReadFragment();
break;
case 2:
fragment = new HelpFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
with this:
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
Intent intent = new Intent(this, MyCustomActivity.class);
startActivity(intent)
break;
case 2:
Intent intent2 = new Intent(this, MyCustomActivity.class);
startActivity(intent2)
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
But when i try on my device, the button doesn'n work as if I had not binded action
*********** EDIT 2 ***********
public class MainActivity extends Activity implements View.OnClickListener {
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Create");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_refresh, "Read");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Help");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#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) {
// 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 super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onClick(View arg0) {
System.out.println("DEBUG"+arg0);
//ACTION, arg0 no value
}
}
Create a new Activity Extending your MainActivity which is having the Navigation Drawer.This new Activity will automatically have the navigation Drawer.
Check this answer for further details :
Same Navigation Drawer in different Activities
Did you try to inflate to a new Activity instead of creating a new Fragment in private void selectItem(int position) { ... } I mean, when you get the position, to create an Intent for the current activity Intent intent = new Intent(this, YourCustomActivity.class); and to navigate to it with startActivity(intent)

android Navigation-drawer ,switching between fragment

When i switch between fragments in Navigation-drawer, Navigation-drawer closes slowly , i assume it waits to replace the newly selected fragment and closes the drawer,
How can i speed up it? In Gmail app, when you select a tab in Navigation-drawer,the new fragment is not created immediately,instead it shows a ProgressBar,then content is load,Also Navigation-drawer closing is speed here.
How can i do it, Any code example is appreciated.
Edit
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.....
navigationDrawerTitles = getResources().getStringArray(R.array.navigation_drawer_titles);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, navigationDrawerTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
.......
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch(position){
case 0:
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, new HomeFragment(), "HomeFragment").commit();
mDrawerList.setItemChecked(position, true);
setTitle(navigationDrawerTitles[position]);
break;
case 1:
getFragmentManager().beginTransaction()
.replace(R.id.content_frame, new HistoryFragment(), "HistoryFragment").commit();
mDrawerList.setItemChecked(position, true);
setTitle(navigationDrawerTitles[position]);
break;
case 2:
Intent sintent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(sintent);
break;
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
Thanks,
I think this link will help you: Speed up Android Navigation drawer
public boolean smoothSlideViewTo(... int duration) {
...
return forceSettleCapturedViewAt(... int duration);
}
You have to close drawer when you replace fragment like this:
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawers();
}else{
drawerLayout.openDrawer(Gravity.START);
}
// your code to replace or add fragment
NOTE:- Change Gravity.START to Gravity.END if your drawer is open from right side. first close drawer and then replace fragment

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.

Categories

Resources