Set selected item in Android BottomNavigationView

前端 未结 21 2312
谎友^
谎友^ 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:08

    I made a bug to Google about the fact that there's no reliable way to select the page on a BottomNavigationView: https://code.google.com/p/android/issues/detail?id=233697

    NavigationView apparently had a similar issue, which they fixed by adding a new setCheckedItem() method.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 15:12

    It is now possible since 25.3.0 version to call setSelectedItemId() \o/

    0 讨论(0)
提交回复
热议问题