导航视图点击事件

2024-01-02

我正在使用 Android Studio 模板中的 android 导航抽屉式导航菜单。如何根据 id 导航到不同的活动。

DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);

        // 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_gallery, R.id.nav_slideshow,
                R.id.nav_tools, R.id.nav_share, R.id.nav_send)
                .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 onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.admin_panel_navigation, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.onNavDestinationSelected(item, navController)
                || super.onOptionsItemSelected(item);
    }

image I tried the below set of codes, but it doesn't perform the click operation.

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    // Handle navigation view item clicks here.
    switch (item.getItemId()) {

       case R.id.nav_maths: {
      //do somthing
            break;
        }  
    }
    //close navigation drawer
    mDrawerLayout.closeDrawer(GravityCompat.START);
    return true;
}

我知道我错过了一些东西,但我无法找到解决方案。谁能帮帮我吗。


根据将目的地绑定到菜单项部分 https://developer.android.com/guide/navigation/navigation-ui#Tie-navdrawer,导航使用您添加到菜单 xml 中的 ID,将它们与导航图 xml 文件中的目的地进行匹配。

因此,如果您有一个菜单项,例如

<item
    android:id="@+id/nav_maths"
    android:icon="@drawable/maths"
    android:title="@string/maths" />

并希望它启动不同的活动,您可以添加一个<activity>导航图的目的地:

<activity
    android:id="@+id/nav_maths"
    android:name="com.your.package.MathsActivity" />

由于它们具有相同的 ID,因此当您单击菜单中的该项目时,您的活动就会启动。

请注意,导航侧重于只有一个活动,因此活动目的地应被视为图表的退出点 - 您的第二个活动将有自己的导航图等,与第一个活动完全分开。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

导航视图点击事件 的相关文章

随机推荐