带有导航视图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;
    }

如何通过导航组件实现这一目标? 谢谢!

解决方法

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

如果您使用自定义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
    }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...