0

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;
}

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


更新 2

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

这解决了它!

4

1 回答 1

1

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

    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")
    }
于 2020-11-21T19:55:31.217 回答