[英]how to perform an action instead of moving to another destination if I click a menu in Navigation Drawer using Navigation Component?
I am trying to use Jetpack Navigation component.我正在尝试使用 Jetpack Navigation 组件。 so navigation component will automatically handle if I want to segue from a destination to another destination when I click a menu in the navigation drawer因此,当我单击导航抽屉中的菜单时,如果我想从一个目的地转到另一个目的地,导航组件将自动处理
but I want to perform an action if a menu is clicked, say for example if a menu in drawer is clicked then I want to show a toast message.但是我想在单击菜单时执行一个操作,例如,如果单击抽屉中的菜单,那么我想显示一条吐司消息。
in old way, ie using fragment transaction, I can easily check from onNavigationItemSelected
, but I am no longer find that method以旧方式,即使用片段事务,我可以轻松地从onNavigationItemSelected
检查,但我不再找到该方法
so how to do that in navigation component ?那么如何在导航组件中做到这一点呢?
I have tried to check onDestinationChanged
, but it doesn't work我试图检查onDestinationChanged
,但它不起作用
override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) {
if (destination.id == R.id.my_destination {
// show toast in here
// but it doesn't work
}
}
here is my MainActivity这是我的主要活动
class MainActivity : AppCompatActivity() {
private lateinit var navController : NavController
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
appBarConfiguration = AppBarConfiguration(setOf(
R.id.destination_share,
R.id.destination_message,
R.id.destination_chat),
drawer_layout
)
// init nav controller
navController = Navigation.findNavController(this,R.id.nav_host_fragment)
// set toolbar
setSupportActionBar(toolbar)
// set up navigation drawer
NavigationUI.setupActionBarWithNavController(this,navController, appBarConfiguration)
NavigationUI.setupWithNavController(navigation_view,navController)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController,appBarConfiguration)
}
}
You can handle Menu clicks as following您可以按如下方式处理菜单点击
navView.menu.findItem(R.id.logout)
.setOnMenuItemClickListener { menuItem: MenuItem? ->
// write your code here
true
}
Have you tried using你有没有试过使用
bottom_nav_view.setOnNavigationItemSelectedListener {
if (destination.id == R.id.my_destination {
// show toast in here
// but it doesn't work
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.