Update selected state of navigation drawer after back press

后端 未结 6 1155
臣服心动
臣服心动 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:57

    I have had alot of trouble trying to figure out a solution to this problem and the solution I ended up using isn't "nice" in my opinion, but it works.

    In my application i ended up adding a fragments position in the navigation drawer, when i added the fragment to the backstack. This way i could call setItemChecked with the position in my onBackStackChanged(). So basicly what i did was this:

    @Override
    public void onBackStackChanged() {
        FragmentManager fm = getFragmentManager();
        String name = fm.getBackStackEntryAt(fm.getBackStackEntryCount()-1).getName();
        mDrawerList.setItemChecked(Integer.parseInt(name),true);
    }
    
    public class DrawerItemClickListener implements android.widget.AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);
        }
    }
    
    private void selectItem(int position) {
        Fragment fragment;
    
        switch (position) {
            case 0: // Home
                fragment = new ContentFragment();
                break;
            case 1: // Another
               fragment = new AnotherFragment();
                break;
            default: // Logout
            {
                finish();
    
                Intent intent = new Intent(this, StartupActivity.class);
                startActivity(intent);
    
                return;
            }
        }
    
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.content_frame, fragment)
                .addToBackStack(Integer.toString(position))
                .commit();
    
        mDrawerList.setItemChecked(position, true);
        setTitle(mNavigationItems[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    

提交回复
热议问题