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

前端之家收集整理的这篇文章主要介绍了android – 按下后退按钮后重新选择正确的NavigationView菜单项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 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;
    }

谢谢.

解决方法

我通过像这样重写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);
            }
        }
    }

}
原文链接:https://www.f2er.com/android/316111.html

猜你在找的Android相关文章