我正在 android studio 中使用 id 在组中添加菜单。我遇到了菜单点击事件的问题,因为当我点击它时它不会做任何事情。
这是我尝试过的:
public boolean onOptionsItemSelected(MenuItem item) { 片段 newFragment = null; // 这是你要放入FrameLayout的片段 int id = item.getItemId();
if (id == R.id.nav_group1) {
newFragment = new FolderFragment();
}
// Let's put the new fragment into the FrameLayout
// If you use the support action bar, use getSupportFragmentManager(), else getFragmentManager()
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_host_fragment, newFragment); // R.id.fragment_container = FrameLayout ID
transaction.commit();
return true;
}
这是我用来添加菜单的:
NavigationView navigationView = findViewById(R.id.nav_view);
Menu menu = navigationView.getMenu();
try {
JSONArray jsonArray = new JSONArray(folders);
int id = 1;
int order = 100;
for (int i = 0; i < jsonArray.length(); i++) {
String folder = jsonArray.getString(i);
menu.add(R.id.nav_group1, id, order, folder)
.setIcon(R.drawable.ic_baseline_folder_24);
id++;
order++;
}
} catch (JSONException e) {
e.printStackTrace();
}
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_inbox, R.id.nav_important, R.id.nav_sent, R.id.nav_drafts, R.id.nav_spam, R.id.nav_trash, R.id.nav_group1, R.id.nav_create_new_folder, R.id.nav_contact)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
我想要实现的是当我点击菜单时,我想打开 nav_group
下的片段。
你能否给我举个例子,当我使用 java 添加菜单时,我如何点击菜单打开片段?