Update selected state of navigation drawer after back press

后端 未结 6 1153
臣服心动
臣服心动 2021-02-19 22:56

Whats the proper way to handle the selected state of the navigation drawer after back press?

I have a navigation drawer with n entries (in a listview) like the SDK sampl

6条回答
  •  我在风中等你
    2021-02-19 23:58

    Building upon @matiash 's excellent answer (be sure to +1 his/hers if you +1 my answer)

    To start, we're assuming we're in the Activity

    getFragmentManager().addOnBackStackChangedListener(
        new FragmentManager.OnBackStackChangedListener() {
            public void onBackStackChanged() {
                // Update your UI here.
            }
        });
    

    You can find the current fragment with the following:

    (from https://stackoverflow.com/a/24589081/878159)

    Fragment f = getFragmentManager().findFragmentById(R.id.frag_container);
    if (f instanceof CustomFragmentClass) {
        // do something with f
        f.doSomething();
    }
    

    That should get you a step closer. Then something like this will get you a reference to your nav drawer:

    nav = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.nav);
    

    Then depending how you setup your drawer fragment code:

    nav.updateSelected(position);
    

    The updateSelected(int) method would be in your NavigationDrawerFragment class and might look something like this:

    public void updateSelected(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
    }
    

    NOTE: there are many ways to do this, but this should get you started.

提交回复
热议问题