Set selected item in Android BottomNavigationView

前端 未结 21 2355
谎友^
谎友^ 2020-11-27 14:16

I am using the new android.support.design.widget.BottomNavigationView from the support library. How can I set the current selection from code? I realized, that

21条回答
  •  一向
    一向 (楼主)
    2020-11-27 15:12

    For those, who still use SupportLibrary < 25.3.0

    I'm not sure whether this is a complete answer to this question, but my problem was very similar - I had to process back button press and bring user to previous tab where he was. So, maybe my solution will be useful for somebody:

    private void updateNavigationBarState(int actionId){
        Menu menu = bottomNavigationView.getMenu();
    
        for (int i = 0, size = menu.size(); i < size; i++) {
            MenuItem item = menu.getItem(i);
            item.setChecked(item.getItemId() == actionId);
        }
    }
    

    Please, keep in mind that if user press other navigation tab BottomNavigationView won't clear currently selected item, so you need to call this method in your onNavigationItemSelected after processing of navigation action:

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.some_id_1:
                // process action
                break;
            case R.id.some_id_2:
                // process action
                break;
            ...
            default:
                return false;
        }
    
        updateNavigationBarState(item.getItemId());
    
        return true;
    }
    

    Regarding the saving of instance state I think you could play with same action id of navigation view and find suitable solution.

提交回复
热议问题