按下后退按钮后重新选择正确的NavigationView菜单项

时间:2015-12-12 16:44:23

标签: android android-fragments

我有一个Android应用程序,它有一个带有4个片段的NavigationView。我可以通过导航菜单在片段之间导航,当我选择另一个片段时,我将前一个片段添加到后栈中以提供后退按钮功能。

我的问题是当我按下后退按钮转到上一个片段时,NavigationView仍会将旧片段显示为所选片段。如果可能,我想将所选选项更新为屏幕上的片段。

例:
我从A开始,从NavigationView中选择B.当前屏幕为B,NavigationView将所选项目显示为B.如果按下后退按钮,我当前屏幕再次变为A,但NavigationView将B显示为所选项目。

这是我的onNavigationItemSelected方法:

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        HomeFragment fragment = null;
        Class type = null;
        switch (id) {
            case R.id.nav_home:
                type = HomeNavigationFragment.class;
                break;
            case R.id.nav_groups:
                type = GroupsNavigationFragment.class;
                break;
            case R.id.nav_profile:
                type = ProfileNavigationFragment.class;
                break;
            case R.id.nav_messages:
                type = MessageNavigationFragment.class;
                break;
        }
        fragment = HomeFragment.newInstance(mUser, type);
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.fragment_container, fragment).addToBackStack("fragment" + code++).commit();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

感谢。

1 个答案:

答案 0 :(得分:14)

我通过像这样重写onBackPressed解决了我的问题:

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        FragmentManager manager = getSupportFragmentManager();
        if(manager.getBackStackEntryCount() > 0) {
            super.onBackPressed();
            HomeFragment currentFragment = (HomeFragment) manager.findFragmentById(R.id.fragment_container);
            if(currentFragment instanceof HomeNavigationFragment){
                mNavigationView.getMenu().getItem(0).setChecked(true);
            }
            else if(currentFragment instanceof GroupsNavigationFragment){
                mNavigationView.getMenu().getItem(2).setChecked(true);
            }
            else if(currentFragment instanceof ProfileNavigationFragment){
                mNavigationView.getMenu().getItem(1).setChecked(true);
            }
            else if(currentFragment instanceof MessageNavigationFragment){
                mNavigationView.getMenu().getItem(3).setChecked(true);
            }
        }
    }

}