如何扩大Android选项菜单并将某个项目设置为Enabled=false?

4nkexdtk  于 2023-02-02  发布在  Android
关注(0)|答案(3)|浏览(118)

我的XML菜单定义将项目www.example.com_refresh的启用状态设置为false。当应用运行时,菜单项呈灰色并被禁用。为什么应用中的此代码不启用该项目?R.id.menu_refresh's enabled state to false. When the app runs the menu item is greyed and disabled. Why is this code in the app not enabling the item?

public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    MenuItem refresh = menu.getItem(R.id.menu_refresh);
    refresh.setEnabled(true);
    return true;
}

我错过了什么?

vkc1a9a2

vkc1a9a21#

尝试使用menu.findItem()代替getItem()getItem()从[0,size)获取索引,而findItem()获取id。

ruoxqz4g

ruoxqz4g2#

这是我在菜单处理活动中所做的...

//Android Activity Lifecycle Method
// This is only called once, the first time the options menu is displayed.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
}

//Android Activity Lifecycle Method
// Called when a panel's menu is opened by the user.
@Override
public boolean onMenuOpened(int featureId, Menu menu)
{
    MenuItem mnuLogOut = menu.findItem(R.id.main_menu_log_out_id);
    MenuItem mnuLogIn = menu.findItem(R.id.main_menu_log_in_id);
    MenuItem mnuOptions = menu.findItem(R.id.main_menu_options_id);
    MenuItem mnuProfile = menu.findItem(R.id.main_menu_profile_id);

    //set the menu options depending on login status
    if (mBoolLoggedIn == true)
    {
        //show the log out option
        mnuLogOut.setVisible(true);
        mnuLogIn.setVisible(false);

        //show the options selection
        mnuOptions.setVisible(true);

        //show the edit profile selection
        mnuProfile.setVisible(true);
    }
    else
    {
        //show the log in option
        mnuLogOut.setVisible(false);
        mnuLogIn.setVisible(true);

        //hide the options selection
        mnuOptions.setVisible(false);

        //hide the edit profile selection
        mnuProfile.setVisible(false);
    }

    return true;
}

//Android Activity Lifecycle Method
// called whenever an item in your options menu is selected
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId())
    {

    case R.id.main_menu_log_in_id:
    {
        ShowLoginUI();
        return true;
    }

    case R.id.main_menu_log_out_id:
    {
        ShowGoodbyeUI();
        return true;
    }

    case R.id.main_menu_options_id:
    {
        ShowOptionsUI();
        return true;
    }

    case R.id.main_menu_profile_id:
    {
        ShowProfileUI();
        return true;
    }

    default:
        return super.onOptionsItemSelected(item);
    }
}

我喜欢这种方法,因为它使代码变得美观和模块化

r55awzrz

r55awzrz3#

使用menu.findItem()代替getItem(),因为findItem用于按ID查找项目。

相关问题