Switching activities using buttons in a main activity with a navigation drawer - android

I've looked up quite a few of the questions asked about the navigation drawer and buttons and many of them are geared towards the button used for the navigation drawer itself. My question is that I can't get a button move to the next activity from the main activity that has a navigation drawer. It creates the button but the clicker doesn't move to the following activity, nor will it throw a toast to let me know that the clicker is working.
I used the template that eclipse gives you when you create a new navigation drawer.
public class UserMain extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
Button one;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_main);
one = (Button) findViewById(R.id.button1);
System.out.println("Button1");
one.setOnClickListener(new View.OnClickListener() {
//There is a problem here!!!
#Override
public void onClick(View v) {
System.out.println(v.toString());
System.out.println("Button 1 pressed!");
// TODO Auto-generated method stub
Context context = getApplicationContext();
CharSequence text = "ONE";
int duration = Toast.LENGTH_SHORT;
Toast passwordToast = Toast.makeText(context, text, duration);
passwordToast.show();
}
});
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
}

Related

How to use nav drawer in multiple activities

I want to define a single nav drawer I can use throughout my application. I followed the instructions of the chosen answer here as my first approach: Same Navigation Drawer in different Activities
I made a few modifications, namely calling onCreateDrawer from inside an overridden onCreate. I updated my subsequent activity to extend DashboardActivity ("base activity" from the example). When I launch my second activity I get a null pointer exception complaining that the nav UI doesn't exist when onCreateDrawer tries to set the toggle listened on the drawer.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
Here are the base (dashboard) and subsequent (log workout) activity - please ask if there is other code you want to see. The code for the UI of the drawer and associated activity are what came out of the box when creating a new Nav Drawer Activity in Android Studio.
DashboardActivity.java
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
onCreateDrawer();
Realm realm = Realm.getDefaultInstance();
RealmQuery<Exercise> query = realm.where(Exercise.class);
RealmResults<Exercise> result = query.findAll();
Log.d(TAG, "There are " + result.size() + " exercises ready for use.");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent logWorkoutIntent = new Intent(getApplicationContext(), LogWorkoutActivity.class);
startActivity(logWorkoutIntent);
}
});
//TODO: Remove this sign out button
Button signOutButton = (Button) findViewById(R.id.button_sign_out);
signOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Signed out", Toast.LENGTH_LONG).show();
}
});
//TODO: Remove this data tester
updateUserName();
}
//#Override
protected void onCreateDrawer() {
Log.d(TAG, "onCreateDrawer called");
//super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
...
-
LogWorkoutActivity.java
public class LogWorkoutActivity extends DashboardActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_log_workout);
setContentView(R.layout.activity_log_workout);
super.onCreateDrawer();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
I think you are missing a drawer with id drawer_layout in your activity_log_workout layout.
In order for this approach to work, you must have a DrawerLayout with id drawer_layout in all your activity layouts that should have the drawer.
I also noticed something peculiar with your code. In every activity that extends DashboardActivity you are first setting setContentView(R.id.activity_dashboard), then calling onCreateDrawer(), then you are changing the content view and creating the drawer again. I think this a very suboptimal approach.
I suggest you create a BaseDrawerActivity class to encapsulate the drawer creation and UI binding logic. Then you just extend it in the activities where you need a drawer. You can do it like this:
public abstract class BaseDrawerActivity extends AppCompatActivity {
// move all your drawer related fields here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
setContentView(getLayoutResId());
// the same method you have right now
onCreateDrawer();
}
/*
* Extending activities use this class to supply the
* id of their layout file. This way you can set the view
* only once and there is no need to create the drawer twice.
*/
#LayoutResId
public abstract int getLayoutResId();
}

Disable Navigation Drawer on start

I want my navigation drawer to be disabled as the application loaded, and if user to some certain tasks it would be enabled.
in brief is there a way to disable navigation drawer's toggle button, and enable it again with subject to a user action.
Edit :
I have updated my activity as follows;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
DrawerLayout navigationDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
navigationDrawerLayout);
navigationDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
}
#Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
if (item.getItemId() == android.R.id.home) {
}
return super.onOptionsItemSelected(item);
}
...
}
but when the application launches I can open navigation drawer, which I don t desire
You just have to lock and unlock your DrawerLayout using DrawerLayout setDrawerLockMode() method.
So, for locking your DrawerLayout in close mode, use:
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
If you prefer to lock it in open mode, use drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
Finally, when you want to unlock your DrawerLayout, use:
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
write condtion in onoptionsitemselected and block it
#Override
public boolean onOptionsItemSelected(android.view.MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if(yourconditionsatisfied)
{
if (mDrawerLayout.isDrawerOpen(mDrawerLinearLayout)) {
mDrawerLayout.closeDrawer(mDrawerLinearLayout);
} else {
mDrawerLayout.openDrawer(mDrawerLinearLayout);
}
}
}
return super.onOptionsItemSelected(item);
}

Why does my Java object reference an old activity after orientation change?

Background:
I have a FragmentActivity that uses a DrawerLayout. I created a class called NavDrawerManager to abstract out the code for dealing with the drawer layout. To construct this object, I need to pass in and keep a reference to an Activity. I use this activity reference to call findViewById(), and I also use the activity as a context when creating a list adapter, etc. I keep a reference to a NavDrawerManager object in my activity so I can perform callbacks and operations on the drawer layout.
UPDATE: Per Xaver's suggestion, I switched to extend FragmentActivity into a NavDrawerActivity. Instead of having a NavDrawerManager object in my activity, the superclass handles the nav drawer code. See updated code.
Issue:
Everything works fine until I change orientations. After changing orientations, it appears that my NavDrawerActivity still references the old layout. I say this because I have a progress bar and a couple of buttons in the DrawerLayout that I am attempting to update, but they don't reflect the updates.
When I call Activity.findViewById() to get the progress bar and make it visible, it doesn't show any changes, nor do any of the changes to the buttons show. Note: Activity.findViewById() does not return null. However, if I do the same things before changing orientation, the progress bar and buttons show the appropriate changes.
Code:
NavDrawerActivity:
public class NavDrawerActivity extends LowProfileFragmentActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ExpandableListView mDrawerList;
private NavDrawerAdapter mListAdapter;
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
mDrawerToggle.onOptionsItemSelected(item);
return super.onOptionsItemSelected(item);
}
//Called via subclass after setContentView
protected void setupNavDrawer() {
initDrawerLayout();
initDrawerList();
setButton1();
setButton2();
}
private void initDrawerLayout() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = getActionBarDrawerToggle();
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void initDrawerList() {
mDrawerList = (ExpandableListView) mDrawerLayout
.findViewById(android.R.id.list);
mListAdapter = getNavDrawerAdapter();
}
private ActionBarDrawerToggle getActionBarDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_navigation_drawer, 0, 0) {
public void onDrawerClosed(View view) {
}
public void onDrawerOpened(View view) {
}
};
}
public void setDrawerLoading(boolean loading) {
ProgressBar progressBar = (ProgressBar) mDrawerLayout
.findViewById(R.id.progress_bar);
Button button1 = (Button) this.findViewById(R.id.button1);
Button button2 = (Button) this
.findViewById(R.id.button2);
/* None of the below changes appear after changing orientation */
if (loading) {
button1.setEnabled(false);
button2.setEnabled(false);
progressBar.setVisibility(View.VISIBLE);
} else {
progressBar.setVisibility(View.GONE);
button1.setEnabled(true);
button2.setEnabled(true);
}
}
private void setButton1() {
Button button1 = (Button) this.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
}
private void setButton2() {
Button button2 = (Button) this
.findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
}
}
ExampleActivity:
public class ExampleActivity extends NavDrawerActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initUI();
}
private void initUI() {
setContentView(R.layout.activity_sift);
// Call the superclass method to set up the nav drawer
setupNavDrawer();
}
}
AndroidManifest.xml:
<activity
android:name="com.example.app.ExampleActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Wouldn't it be easier if you implemented a NavDrawerActivity instead of a NavDrawerManager? Generally things like this should be avoided. The UI should be handled solely by the Fragments or Activities themselves.
I understand why you would want to create such a NavDrawerManager, simply to make the whole thing reusable and a lot of abstraction is great, but when it is overdone it can become a problem. Don't focus so much on everything being perfectly abstracted and according to OOP standards. There is nothing wrong with an Activity having both a NavigationDrawer and hiding the notification bar. And if you already have an Activity that implements one of those two things you should extend it. Your only other option would be to reimplement the same behaviour in a second Activity and that would pretty much defeat the purpose of abstraction.
EDIT: I have refactored and improved your code, you really should not have so many different methods for everything, all the setup belongs in onCreate(), that you write extra methods for each step just introduces the possibility for additional errors. Try this:
public abstract class NavDrawerActivity extends LowProfileFragmentActivity {
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawerLayout;
private ProgressBar progressBar;
private Button button1;
private Button button2;
private ExpandableListView drawerList;
private NavDrawerAdapter drawerListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
this.drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
this.drawerToggle = new ActionBarDrawerToggle(this, this.drawerLayout, R.drawable.icon_drawer, R.string.drawer_open, R.string.drawer_close);
this.drawerLayout.setDrawerListener(this.drawerToggle);
this.drawerList = (ExpandableListView) this.drawerLayout.findViewById(android.R.id.list);
this.progressBar = (ProgressBar) this.drawerLayout.findViewById(R.id.progress_bar);
this.button1 = (Button) findViewById(R.id.button1);
this.button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
this.button2 = (Button) findViewById(R.id.button2);
this.button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
this.drawerListAdapter = new NavDrawerAdapter(...);
this.drawerList.setAdapter(this.drawerListAdapter);
}
protected abstract int getLayout();
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
this.drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return this.drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
public void setDrawerLoading(boolean loading) {
this.button1.setEnabled(!loading);
this.button2.setEnabled(!loading);
this.progressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
}
}
As you can see I use an abstract method called getLayout() to pass the correct layout to setContentView(). getLayout() has to be implemented by all Activities which extend the NavDrawerActivity therfore giving the sub Activities control over the used layout.
As such your ExampleActivity should look like this:
public class ExampleActivity extends NavDrawerActivity {
#Override
protected int getLayout() {
return R.layout.activity_sift;
}
}
I tested everything and it's working for me.

How do I change my button image with navigation drawer opening and closing

I have a navigation button for my navigation fragment which turns active and opens a navigation drawer menu upon click:
Now when I click it, it turns active as follows:
However, I want to associate it with a navigation drawer such a way that, even if I do not click the button and slide open the navigation drawer, the button turns active when the navigation drawer menu is open and when closed by sliding back in from right to left, the button turns red/inactive. The code which I am trying to work with is as follows:
private boolean mIsNavigationOpen = false;
private DrawerLayout drawerLayout;
private NavigationPanelFragment dlDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
public boolean isNavigationOpen() {
return mIsNavigationOpen;
}
//----------Code for Navigation open logo button active/inactive instances
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
this.mIsNavigationOpen = isNavigationOpen;
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
//----------Code for Navigation Drawer setup
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close){
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
// getActionBar().setTitle(NavigationPanelFragment.activeFragmentTitle);
// invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
// getActionBar().setTitle(NavigationPanelFragment.activeFragmentTitle);
// invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
//For swipe action close drawer on button click
drawerLayout.closeDrawer(R.id.drawer);
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
//For swipe action close drawer on button click
drawerLayout.closeDrawer(R.id.drawer);
}
private void toggleNavigationPanel() {
//final FragmentStackManager manager = FragmentStackManager.getInstance();
if (mIsNavigationOpen) {
//NavigationPanelFragment.removeInstance(getSupportFragmentManager());
updateActionBarTitle();
drawerLayout.closeDrawer(R.id.drawer);
} else {
drawerLayout.openDrawer(R.id.drawer);
final TextView title = (TextView) findViewById(R.id.main_title);
title.setText(getString(R.string.title_applications));
//NavigationPanelFragment.newInstance(getSupportFragmentManager(), manager.getTopTitle());
}
setNavigationOpen(!mIsNavigationOpen);
}
You might want to concentrate on the main_button and togglenavigationpanel. I added the condition if(drawerlayout.isdraweropen(R.id.drawer)){closedrawerlayout...}
but it didn't do the trick. I was wondering if anyone has any idea regarding the same?
Thanks!
When you've set up the drawer a listener has been added which has callbacks for when the drawer is in either final state, so what you need to do is reset the drawable inside these callbacks. I've shown what I think your final code should look like, minus some cleaning up you need to do, hope it helps
private DrawerLayout drawerLayout;
private NavigationPanelFragment dlDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
private ImageButton mDrawerButton; //Store it! - findViewById is *Expensive*
private TextView mTitle;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mTitle = (TextView) findViewById(R.id.main_title);
mDrawerButton = (ImageButton) findViewById(R.id.button_main);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
mDrawerButton.setImageResource(R.drawable.bg_helios_inactive);
}
public void onDrawerOpened(View drawerView) {
mDrawerButton.setImageResource(R.drawable.bg_helios_active);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
setupOnClickListenerForMainButton(;
}
#Override //Note: I'd imagine this should be in onResume ...
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
private void setupOnClickListenerForMainButton() {
mDrawerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
...
private void toggleNavigationPanel() {
//if ( drawerLayout.isOpen() ) { //I dont know what methods these objects have
if ( dlDrawer.isOpen() ) { //but one of these must be sensibly storing its own state
updateActionBarTitle();
drawerLayout.closeDrawer(R.id.drawer);
} else {
drawerLayout.openDrawer(R.id.drawer);
mTitle.setText(getString(R.string.title_applications));
}
}

navigation drawer and fragment back stack handler

I keep reading about fragment and fragment back handling but still couldn't find a best solution here.
I have navigation drawer.
Lets pretend I have 2 items in my navigation drawer list (item1,item2)
when I click on item1 it's open A Fragment. in A Fragment after clicking in button opens B Fragment. So when B fragment is opened and I choose item2 from navigation drawer opens C Fragment.
And now when I press back button it should finish activity not go to B Fragment.
So in one word when I choose item1,item2 opens A fragment or C fragment, after pressing back button should finish activity but when opens B fragment(which is under item1) it have to go back to A Fragment
Please help it is very difficult for me. Thanks
public class MainActivity extends DefaultActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggleWrapper mDrawerToggle;
private ListView mDrawerListView;
private TextView mTitle;
private Runnable mPendingRunnable;
private Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDrawerListView = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mFragmentManager = getSupportFragmentManager();
mHandler = new Handler();
LayoutInflater inflator = (LayoutInflater) this .getSystemService(LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.custom_view, null);
mTitle = (TextView)v.findViewById(R.id.title);
getSupportActionBar().setBackgroundDrawable(null);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setIcon(R.drawable.button_indicator_menu);
getSupportActionBar().setCustomView(v);
v.findViewById(R.id.menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mDrawerLayout.isDrawerOpen(GravityCompat.START)){
mDrawerLayout.openDrawer(GravityCompat.START);
}else {
mDrawerLayout.closeDrawers();
}
}
});
mDrawerToggle = new ActionBarDrawerToggleWrapper(this, mDrawerLayout, R.drawable.transparent_gic, R.string.drawer_open, R.string.drawer_close){
public void onDrawerClosed(View view) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
mPendingRunnable = null;
}
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.addPartnerToggle(new ContentDisplaceDrawerToggle(this, mDrawerLayout, R.id.content_frame));
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
setLeftDrawerLeftMenu();
getFragment(getString(R.string.home));
setTitle(getString(R.string.home));
}
private void setLeftDrawerLeftMenu(){
final ArrayList<Item> items = new ArrayList<Item>();
items.add(new SectionItem(this,"icons_small_home",getString(R.string.home)));
items.add(new SectionItem(this,"icons_small_myacounts",getString(R.string.my_account)));
items.add(new EntryItem(getString(R.string.bonuses)));
items.add(new EntryItem(getString(R.string.account_recharge)));
items.add(new EntryItem(getString(R.string.tariff_plans)));
items.add(new EntryItem(getString(R.string.languages)));
EntryAdapter adapter = new EntryAdapter(MainActivity.this, items);
mDrawerListView.setAdapter(adapter);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
EntryItem item = (EntryItem) items.get(i);
setTitle(item.getTitle());
}
});
}
public void setTitle(final String title){
mTitle.setText(title);
mPendingRunnable = new Runnable() {
#Override
public void run() {
getFragment(title);
}
};
mDrawerLayout.closeDrawers();
}
public void getFragment(String name){
if(getString(R.string.orange_shops).equalsIgnoreCase(name)){
if (!(mSelectedFragment instanceof OrangeShopsFragment)){
addPage(new MyFragment(MainActivity.this),true);
}
}else if(getString(R.string.home).equals(name)){
addPage(new HomeFragment(MainActivity.this),false);
}else{
throw new RuntimeException("unknown fragment "+ name);
}
}
public void addPage(final DefaultFragment pDefaultFragment, final boolean isAddToBackStack){
FragmentTransaction transaction = mFragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, pDefaultFragment);
if (isAddToBackStack) transaction.addToBackStack(null);
transaction.commitAllowingStateLoss();
}
}
It's not so difficult to clear the backstack.
Whenever the user clicks on any item on the drawer, just call
while(getSupportFragmentManager.popBackStackImmediate()){}
to clear what you had before.
edit:
I know it's a old question but I found a better/more efficient way of doing it using:
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
that was answered in the groups.google.com by one of the Android engineers, I replaced it on my app and the "clear stack" command works much faster now. Hope it helps.
I also faced this problem while working with fragments and navigation drawer. When we are navigating from one fragment to another fragment they all are added to same backstack. So that's why you are getting this problem. Inorder to overcome this problem i myself maintained back stack and handled the on backpressed method
If you post your code i will suggest a nice solution for your problem

Categories

Resources