我正在开发一个带有侧边导航抽屉的应用程序。抽屉可以正常打开,但是应该可以“点击”的文本似乎没有响应。动画显示当抽屉被点击时会有反馈(你可以听到声音)然而没有任何结果。我试过放置吐司消息,看看按钮是否注册了一个动作,但是当按下时,没有吐司出现。代码如下(我已经实现了NavigationView.OnNavigationItemSelectedListener):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_history, R.id.nav_settings,
R.id.nav_help, R.id.nav_signout)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
然后我实现了这个方法:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_history:
Toast.makeText(this, "fsdfuxc", Toast.LENGTH_LONG).show();
break;
case R.id.nav_help:
break;
case R.id.nav_settings:
break;
case R.id.nav_signout:
signOut();
break;
}
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
谢谢你
2条答案
按热度按时间wgx48brx1#
行
在内部调用
setNavigationItemSelectedListener
以将目标连接到菜单项(即,当您单击R.id.nav_settings
MenuItem时,它会将NavHostFragment中的Fragment替换为设置了android:id="@+id/nav_settings"
的Fragment)。此侦听器会覆盖您设置的OnNavigationItemSelectedListener
视图,这就是您的自定义逻辑无法运行的原因。如果要将这两组功能组合在一起,则需要在**
setupWithNavController
之后调用navigationView.setNavigationItemSelectedListener(this);
**,并使用NavigationUI.onNavDestinationSelected()
触发默认行为:x0fgdtte2#
只是一个小样本,基于已接受的答案,但在片段内,没有覆盖注解和使用Kotlin。