我是Android的初学者。我已经使用“导航抽屉活动”项目的默认模板创建了“导航抽屉活动”。它工作正常。现在,我需要更改抽屉菜单列表并添加新项目。我在activity_main_drawer.xml中添加了一项,如下所示,它显示正确。
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:showIn="navigation_view"> <group android:checkableBehavior="single"> <item android:id="@+id/nav_home" android:icon="@drawable/ic_menu_camera" android:title="@string/menu_home" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="@string/menu_gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_menu_slideshow" android:title="@string/menu_slideshow" /> <item android:id="@+id/nav_others" android:icon="@drawable/ic_menu_slideshow" android:title="Others" /> </group> </menu>
尽管示例应用程序正在运行,并且在单击菜单项时正在打开片段。但没有onNavigationItemSelected(就像我在其他文档中找到的那样)。我无法得知它们(片段)的调用方式。
主活动的默认代码如下:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private AppBarConfiguration mAppBarConfiguration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); 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_others) .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.main, menu); return true; } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp(); } }
我已如下添加onNavigationItemSelected,但它也无法正常工作。
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_others) {
Toast.makeText(MainActivity.this,id,Toast.LENGTH_LONG).show();
}
return true;
}
我是Android的初学者。我已经使用“导航抽屉活动”项目的默认模板创建了“导航抽屉活动”。它工作正常。现在我需要更改抽屉菜单列表...
在找到视图后在您的MainActivity中: