setOnNavigationItemSelectedListener 已弃用

setOnNavigationItemSelectedListener deprecated

目前我正在开发一个底部导航栏带有三个菜单项的应用程序。我对被点击的项目使用了 setOnNavigationItemSelectedListener()。但现在我面临着该方法已被贬值的问题。

有什么办法可以解决吗?有没有比 setOnNavigationItemSelectedListener() 方法更好的选择。

根据 github 来源不推荐使用:BottomNavigationView.setOnNavigationItemSelectedListener

在其评论中您可以阅读:

@deprecated Use {@link NavigationBarView#setOnItemSelectedListener(OnItemSelectedListener)}
   *     instead.

所以从它的基础 class 使用 NavigationBarView.setOnItemSelectedListener:

  /**
   * Set a listener that will be notified when a navigation item is selected. This listener will
   * also be notified when the currently selected item is reselected, unless an {@link
   * OnItemReselectedListener} has also been set.
   *
   * @param listener The listener to notify
   * @see #setOnItemReselectedListener(OnItemReselectedListener)
   */
  public void setOnItemSelectedListener(@Nullable OnItemSelectedListener listener) {
    selectedListener = listener;
  }

另见此commit

因为它解释了对这一变化的困惑:

The listeners were deprecated in favor of NavigationBarView#OnItemSelectedListener and NavigationBarView#OnItemReselectedListener, but deprecation documentation was never added, so it's unclear what developers should use instead.

你可以试试setonItemSelectedListener。它的工作方式与 setOnNavigationItemSelectedListener()[在 android 11 中测试]

相同
bnv.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int id = item.getItemId();
            switch(id){
              //check id
            }
            return true;
        }
    });

科特林:

bnv.setOnItemSelectedListener { item ->
            when (item.itemId) {
            }
            true
        }

 viewBindingMainActivity.navView.setOnItemSelectedListener { menuItem ->
            if (menuItem.itemId != R.id.navigation_home) {
                Add your code
                false
            } else {
                Add your code
                true
            }
        }

我们可以使用 setOnItemSelectedListener 而不是 setOnNavigationItemSelectedListener 并且 setOnItemReselectedListener 而不是 setOnNavigationItemReselectedListener

navView.setOnItemSelectedListener {
    // do something
    true
}

// In case the default menu can be the first menu 
// Should set the default selected menu BETWEEN setOnItemSelectedListener and setOnItemReselectedListener. 
// It will make setOnItemSelectedListener fired when you launch app. 

// If you set default menu AFTER setOnItemReselectedListener. 
// Then setOnItemReselectedListener will fired when you launch app
navView.selectedItemId = R.id.navigation_home


navView.setOnItemReselectedListener {
    // do something
}