如何在转到后面的片段时更改底部导航视图中的选定项目?

时间:2017-12-11 04:53:13

标签: android

当我按后退键并且片段移动到上一个片段时,我想更改所选的项目ID。

BottomNavigationView navigationView;
navigationView = findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(navigationView);


 navigationView.setOnNavigationItemSelectedListener(item -> {
        switch (item.getItemId()) {
            case R.id.mHome:
                android.support.v4.app.FragmentManager fragmentManager = 
getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction 
fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.mainFrame,new 
HomeFragment()).addToBackStack(null).commit();
                break;

2 个答案:

答案 0 :(得分:0)

覆盖OnBckPressed()并在其中实现FragmentTransaction

@Override
public void onBackPressed() {
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.mainFrame,new  HomeFragment()).addToBackStack(null).commit();
}

答案 1 :(得分:0)

只需在片段的onResume()中添加此行:

((MainActivity)getActivity()).navigationView.setCheckedItem(R.id.this_fragment_menu_id);

其中MainActivity是您加载导航视图的类。