我正在开发一款Android应用。在我的应用程序中,我使用导航抽屉和导航视图。我以编程方式将菜单项添加到抽屉。但是当我添加时,主菜单会出现在子菜单下面。
这是我在onCreate of activity
中添加菜单的方法private static final int CATEGORY_MENU_GROUP_ID = 20;
private static final int MAIN_MENU_ITEM_GROUP_ID = 19;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
updateAuthUI();
addCategoryMenu();
}
这是我的updateAuthUI方法
public void updateAuthUI()
{
isLoggedIn = authStorage.getBoolean(getResources().getString(R.string.pref_is_logged_in),false);
Menu menu = leftDrawer.getMenu();
menu.removeGroup(MAIN_MENU_ITEM_GROUP_ID);
menu.add(MAIN_MENU_ITEM_GROUP_ID,96,1,"Leaderboard").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
startActivity(new Intent(MainActivity.this,LeaderboardActivity.class));
return false;
}
});
if(isLoggedIn)
{
fabBtn.setVisibility(View.VISIBLE);
menu.add(MAIN_MENU_ITEM_GROUP_ID,getResources().getInteger(R.integer.logout_item_id),4,"Sign out").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
logOut();
return false;
}
});
}
else{
fabBtn.setVisibility(View.INVISIBLE);
menu.add(MAIN_MENU_ITEM_GROUP_ID,getResources().getInteger(R.integer.register_item_id),2,"Create Account").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
openRegisterActivity();
item.setChecked(true);
return true;
}
});
menu.add(MAIN_MENU_ITEM_GROUP_ID,getResources().getInteger(R.integer.login_item_id),3,"Sign in").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
openLoginActivity();
item.setChecked(true);
return true;
}
});
}
}
这是addCategoryMenu方法
private void addCategoryMenu()
{
if(categoryItems!=null && categoryItems.size()>0)
{
Menu menu = leftDrawer.getMenu();
SubMenu categorySubMenu = menu.addSubMenu("Categories");
int menuStart = 6;
for(int i = 0;i<categoryItems.size();i++)
{
categorySubMenu.add(CATEGORY_MENU_GROUP_ID,categoryItems.get(i).getId(),menuStart,categoryItems.get(i).getName()).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
categoryItemSelected(item);
item.setChecked(true);
return true;
}
});
menuStart++;
}
}
}
当我运行主菜单时出现在子菜单(类别菜单)下面,如下所示:
为什么会发生这种情况,我该如何解决?