kanytu / android-material-drawer-template

An Android template with navigation drawer for material design
Apache License 2.0
674 stars 217 forks source link

How to select menu position when using popBackStack? #35

Closed zakiharis closed 9 years ago

zakiharis commented 9 years ago

Hi, newbie here.

Let say I have 3 menus (Menu 1, Menu 2, Menu 3)

Then in onNavigationDrawerItemSelected I use addToBackStack for each menu.

After run the app, I select the Menu 2, then I hit the back button, it will show Menu 1 but drawer still highlighting Menu 2.

How to change the drawer highlight?

I know by using selectPosition, but how to get the position?

kanytu commented 9 years ago

You can do that on your fragment's onAttach method. This method will get called when the fragment gets attached on the view. In order to retrieve the position you will need to statically set it on each fragment. I'm afraid there is no way to retrieve the position in a simpler way.

Here is a snippet of a fragments onAttach

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
   NavigationDrawerFragment drawer= (NavigationDrawerFragment) activity.getFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    if(drawer!=null && drawer.getView()!=null){
        RecyclerView recyclerView = (RecyclerView) drawer.getView().findViewById(R.id.drawerList);
        if(recyclerView.getAdapter()!=null){
            ((NavigationDrawerAdapter)recyclerView.getAdapter()).selectPosition(0);
        }
    }
}

Notice the selectPosition(0). You will need to change this position to the position your fragment is taking on the menu. Hope this helps.

marcinkolonko commented 9 years ago

hi, but the onAttach method won't be called when the fragment is coming from the backstack... wouldn't it be better to have it in the onCreateView method?

kanytu commented 9 years ago

Yes you're correct. It's better to call it on onCreateView.