BottomNavigationView启用单击禁用检查

You*_*mal 2 android android-layout android-menu android-view bottomnavigationview

我正在使用具有5个项目,4个片段和1个活动的BottomNavigationView,如下图所示

图片

当用户点击任何片段,我希望它能够正常行动变得clickedchecked,但是当“+”项目被点击,我打开一个活动,但我不希望它是checked,所以我想这是clickable因此它可以打开活动,但我不想成为checked,因为当用户从活动中返回时,即使它是错误选择的项目,也会看到它被选中。我怎样才能做到这一点?

这是我的代码:

bottomNavigationView = findViewById(R.id.bottom_nav_view);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
Run Code Online (Sandbox Code Playgroud)

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    int id = menuItem.getItemId();
    Fragment fragment = null;
    switch (id) {
        case R.id.home_nav_menu:
            fragment = new HomeFragment();
            break;
        case R.id.inbox_nav_menu:
            fragment = new InboxFragment();
            break;
        case R.id.add_nav_menu:
            Intent intent = new Intent(this, AddActivity.class);
            startActivity(intent);
            return true;
        case R.id.history_nav_menu:
            fragment = new HistoryFragment();
            break;
        case R.id.profile_nav_menu:
            fragment = new ProfileFragment();
            break;
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_place_holder, fragment).commit();
    return true;
}
Run Code Online (Sandbox Code Playgroud)

azi*_*ian 9

用户MenuItem#setCheckable(boolean)API 以播放菜单项的可检查状态。


    MenuItem menuItem = navigation.getMenu().getItem(1);
    menuItem.setCheckable(false);

在此处输入图片说明


Uma*_*ain 6

对于底部导航,请参见侦听器的源代码,当您不想显示所选内容时,只需返回false。

 /**
     * Listener for handling selection events on bottom navigation items.
     */
    public interface OnNavigationItemSelectedListener {

        /**
         * Called when an item in the bottom navigation menu is selected.
         *
         * @param item The selected item
         *
         * @return true to display the item as the selected item and false if the item should not
         *         be selected. Consider setting non-selectable items as disabled preemptively to
         *         make them appear non-interactive.
         */
        boolean onNavigationItemSelected(@NonNull MenuItem item);
    }
Run Code Online (Sandbox Code Playgroud)

因此,您只需在自己的代码中返回false即可case R.id.add_nav_menu:

  • 如果您发布带有问题的代码,请参阅@YousefGamal,您将很快得到答案:) (3认同)
  • 那真是太好了,非常感谢 (2认同)