Android NavigationView 的 ReselectedListener

Android ReselectedListener for NavigationView

BottomNavigationView中可以设置:

    bottomNavigationView.setOnNavigationItemReselectedListener(item -> {
        // do nothing on reselection
    });

但是对于 NavigationView 这不可用。什么是好的等价物?


更新

感谢 @ande 我实现了以下内容:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    if (currentMenuItemId == item.getItemId()) {
        navDrawer.close();
        return true;
    }
    currentMenuItemId = item.getItemId();
    NavigationUI.onNavDestinationSelected(item, navController);
    navDrawer.close();
    return true;
}

如果我只通过菜单项导航,这很有效。 (顺便说一句,我刚刚在我的 Activity 中实现了监听器并从那里添加了它,不需要额外的 class)
但是,当我按下后退按钮时,我将能够按下当前目的地的菜单按钮,因为菜单项未在 onBackPressed().

上更新

更新 2

    navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
        @Override
        public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
            currentMenuItemId = destination.getId();
        }
    });

这解决了!

也许你可以这样做(我做的很快所以可能会更好!!)

    class ReSelectedListener(val navigationViewCallBack: NavigationViewCallBack) : NavigationView.OnNavigationItemSelectedListener {

    var newItemSelected : MenuItem? = null
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        if(newItemSelected != null){
            if(newItemSelected!!.itemId == item.itemId){
                navigationViewCallBack.setOnNavigationItemReselectedListener(item)
            }
        }
        newItemSelected = item
        return true
    }


}

interface NavigationViewCallBack {
    fun setOnNavigationItemReselectedListener(item: MenuItem)
}

之后

class YourFragment :Fragment(), NavigationViewCallBack

navigationView.setNavigationItemSelectedListener(ReSelectedListener(this))

并在 YourFragment 中实现回调方法:

 override fun setOnNavigationItemReselectedListener(item: MenuItem) {
        TODO("Not yet implemented")
    }