首页 > 解决方案 > 带有导航视图android的导航组件

问题描述

我正在尝试使用导航组件。
目前我有带菜单的导航视图。
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 = "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;
    }

我如何使用导航组件实现这一目标?谢谢!

标签: javaandroidandroid-architecture-navigationandroid-navigationviewandroid-jetpack-navigation

解决方案


使用导航组件,您不需要手动实现 a OnNavigationItemSelectedListener,因为该setupWithNavController()方法将目的地连接到与android:id导航图和菜单项之间匹配的菜单项。

如果您使用自定义NavigationItemSelectedListener,您将删除原始侦听器。在这种情况下,您必须调用NavigationUI.onNavDestinationSelected()以触发默认行为。

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
    }

推荐阅读