英文:
navigation component with navigation view android
问题
我正试图使用导航组件进行工作。<br>
目前我有带有菜单的导航视图。<br>
我在导航视图中实现了onNavigationItemSelected
,并通过item.getItemId()
来检测点击,
当点击特定项目时,它会执行一些不是导航到片段的操作。例如:
switch (item.getItemId()) {
case R.id.nav_share:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "与朋友一起保持关注,bla bla bla,我们可以将应用程序网址放在Google Play中," +
"如果我们不会是SDK的话";
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "通过以下方式分享"));
break;
case R.id.nav_disconnect_user:
FirebaseAuth.getInstance().signOut();
break;
}
我如何使用导航组件实现这一点?
谢谢!
英文:
I am trying work with navigation component. <br>
currently I have navigation view with menu. <br>
I implement onNavigationItemSelected
in navigation view and detect click by
item.getItemId()
when there is clicks on specific items, it do something that not navigate to fragment. for example:
switch (item.getItemId()) {
case R.id.nav_share:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "shae StayTuned with friends bla bla bla and we can put app url in the google play " +
"if we don't will be sdk";
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
break;
case R.id.nav_disconnect_user:
FirebaseAuth.getInstance().signOut();
break;
}
how I can achieve that with navigation component?
thanks!
答案1
得分: 0
Here's the translated content:
使用导航组件时,您无需手动实现OnNavigationItemSelectedListener
,因为setupWithNavController()
方法会将目标与在导航图和菜单项之间匹配的android:id
连接起来。
如果您使用自定义的NavigationItemSelectedListener
,则会删除原始的监听器。在这种情况下,您需要调用NavigationUI.onNavDestinationSelected()
来触发默认行为。
navigationView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.R.id.nav_share -> {
// 处理点击事件
true
}
}
// 调用原始监听器
NavigationUI.onNavDestinationSelected(it, navController)
drawerLayout.closeDrawer(GravityCompat.START)
true
}
英文:
With the navigation component you don't need to manually implement a OnNavigationItemSelectedListener
since the setupWithNavController()
method connects destinations to menu items matching the android:id
between your navigation graph and menu items.
If you use a custom NavigationItemSelectedListener
you are removing the original listener. In this case you have to call NavigationUI.onNavDestinationSelected()
to trigger the default behavior.
navigationView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.R.id.nav_share -> {
// handle click
true
}
}
//Call the original listener
NavigationUI.onNavDestinationSelected(it, navController)
drawerLayout.closeDrawer(GravityCompat.START)
true
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论