设置菜单项code作为托运 [英] Set a menu item as checked from code

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

问题描述

我有一个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>

和作为应用程序状态的改变,我希望能够到上次使用的时间与以下code pre-检查哪些项目的排序选项列表:

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?

一看日志显示,运行时异常是由一个空指针异常触发。通过改变code以这种方式:

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);

这在秒内声明,即发生异常变得清晰,菜单项MI为空。那么,为什么失败的第一个语句把一个指向正确的菜单项?

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()的菜单,因为它是一个菜单,而不是一个视图。而且它正在创建或prepared时,您可以更改菜单状态。例如,如果您创建一个选项菜单,你可以做到这一点,在活动:在prepareOptionsMenu()方法:

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);
    return true;
}

这篇关于设置菜单项code作为托运的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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