将菜单项设置为从代码中检查 [英] Set a menu item as checked from code

查看:18
本文介绍了将菜单项设置为从代码中检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Android 应用程序,其中一个活动(涉及处理名称和 mac 编号列表)中有以下菜单项:

I have an Android application with the following menu item in one of the Activities (which concerns handling a list of names and mac numbers):

<item android:id="@+id/menu_sort_tagg"
      android:icon="@android:drawable/ic_menu_sort_by_size"
      android:title="@string/menu_sort_list" >
      <menu> 
        <group android:checkableBehavior="single">
            <item android:id="@+id/sort_by_name"
                  android:title="@string/sort_by_name" />
            <item android:id="@+id/sort_by_mac"
                          android:title="@string/sort_by_mac" />

     </menu>
</item>

并且随着应用程序状态的变化,我希望能够使用以下代码预先检查排序选项列表中上次使用的项目:

and as the application state changes, I want to be able to pre-check which item in the sort options list that was used last time with the following code:

((MenuItem)findViewById(R.id.sort_by_name)).setChecked(true);

问题是这个特定的行给了我一个运行时异常.有谁知道为什么?

The problem is that this specific line gives me a runtime exception. Does anyone have a clue why?

查看日志发现运行时异常是由空指针异常触发的.通过这样修改代码:

A look at the log reveals that the runtime exceptions is triggered by a null pointer exception. By changing the code in this way:

MenuItem mi = (MenuItem)findViewById(R.id.sort_by_name);
mi.setChecked(true);

很明显,异常发生在 seconds 语句中,即 MenuItem mi 为 null.那么为什么第一个语句无法将指针指向正确的 MenuItem?

it becomes clear that the exception occurs in the seconds statement, i.e., the MenuItem mi is null. So why fails the first statement to bring a pointer to the correct MenuItem?

推荐答案

你不能对菜单执行 findViewById(),因为它是一个菜单,而不是一个视图.您可以在创建或准备菜单时更改菜单状态.例如,如果你创建了一个选项菜单,你可以在 Activity: onPrepareOptionsMenu() 方法中进行:

You can't do findViewById() for a menu, because it's a menu, not a view. And you can change menu state when it's being created or prepared. For example, if you create an options menu, you can do it in the Activity: onPrepareOptionsMenu() method:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.findItem(R.id.sort_by_name).setChecked(true);
    //Also you can do this for sub menu
    menu.getItem(firstItemIndex).getSubMenu().getItem(subItemIndex).setChecked(true);
    return true;
}

这篇关于将菜单项设置为从代码中检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆