1

I have implemented BottomNavigationView in my app. Everything going easy and perfect but there is one problem i.e. on back press I want to get the currently active tab selected but now selected tab does not change when back press. Fragment changes but tab selection does not change. How can I detect the current tab and change the selected tab on back press. I tried a lot of things to do but not able to get selected tab ID.Please help.

Code:

      int i =   getSelectedItem(bottomNavigationView);
    Log.e("TAG", "onCreate:tab "+i );

      private int getSelectedItem(BottomNavigationView bottomNavigationView){
    Menu menu = bottomNavigationView.getMenu();
    for (int i=0;i<bottomNavigationView.getMenu().size();i++){
        MenuItem menuItem = menu.getItem(i);
        if (menuItem.isChecked()){
            return menuItem.getItemId();
        }
    }
    return 0;
}
Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
mishti
  • 183
  • 7
  • 20
  • take a global variable for id and update it when your select the tab from BottomNavigationView. hence when you press back button it will give you last selected tab item id. – Aniruddh Parihar Nov 21 '18 at 07:25

1 Answers1

3

If you want to find the checked item id, try this:

int checkedItemId = bottomNavigationView.getSelectedItemId();

To change current selected item, use this:

bottomNavigationView.getMenu().findItem(R.id.target_item_nemu).setChecked(true);
aminography
  • 21,986
  • 13
  • 70
  • 74
  • You want its position or menu id? – aminography Nov 21 '18 at 07:10
  • please share more code, where do you want to use it? – aminography Nov 21 '18 at 07:11
  • whatever I can get. Menu id or position. I just need to change tab selection on backpress. but i tried in oncreate and onresume both but not working – mishti Nov 21 '18 at 07:12
  • If I understand correctly, you want to show home fragment in onBackPressed if another fragment is showing, else (if the home fragment is the currently showing), exit the app. Right? – aminography Nov 21 '18 at 07:16
  • no, i have four tabs a,b,c,d. if I selected d fragment then it will be selected. If i press back then it will go to c fragment but still d tab is selected. I want to c tab selected when back press. How can I ? – mishti Nov 21 '18 at 07:22
  • Do you use a ViewPager for managing Fragments? Or simply FragmentManager? – aminography Nov 21 '18 at 07:28
  • I have fragmentManager – mishti Nov 21 '18 at 07:29
  • I thing the problem is to check another item, not finding current checked item. In onBackPressed you can check visibility of fragments using `fragmentA.isVisible()`, then set state of related menu to checked (answer updated). – aminography Nov 21 '18 at 07:43