Spinner作为MenuItem未由findViewById初始化 [英] Spinner as MenuItem not initialized by findViewById

查看:48
本文介绍了Spinner作为MenuItem未由findViewById初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的操作栏上有一个微调器.这是一个菜单项(不是导航模式).它在我从spinnerNumber调用方法的行上给了我一个nullpointerexception. 我认为我在xml上做错了,或者也许我不应该在OnCreateOptionMenu上初始化它(但是我认为当菜单xml仍然没有膨胀时,在OnCreate上调用它也不正确).

I have a spinner on my actionbar. It is a menuitem (not a navigation mode). It gives me back a nullpointerexception on the lines where i call a method from spinnerNumber. I think i'm doing something wrong with the xml or maybe i shouldn't initialize it on OnCreateOptionMenu (but i think that calling it on OnCreate, when the menu xml isn't still inflated, is not correct either).

act_main.xml:

act_main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/numberSpinner"
    android:actionLayout="@layout/spin_number"
    android:showAsAction="always">
</item>
<item
    android:id="@+id/menu_settings"
    android:orderInCategory="100"
    android:showAsAction="ifRoom"
    android:title="@string/menu_settings">
</item>

spin_number.xml

spin_number.xml

   <Spinner xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="wrap_content"
android:layout_height="wrap_content" />

SherlockFragmentActivity中的方法:

The method inside my SherlockFragmentActivity:

public boolean onCreateOptionsMenu(Menu menu) {
    getSupportMenuInflater().inflate(R.menu.act_main, menu);

    spinnerNumber= (Spinner)findViewById(R.id.numberSpinner);


    mAdapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_2, null,
            new String[] { MyContentProvider.Data.N_TITLE, MyContentProvider.Data.N_NUMBER, MyContentProvider.Data.N_ID },
            new int[] { android.R.id.text1, android.R.id.text2 },
            CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

    this.getSupportLoaderManager().initLoader(NUMBERS_LOADER, null, this);

    spinnerNumber.setAdapter(mAdapter);
    spinnerNumber.setOnItemSelectedListener(this);
    spinnerNumber.setSelection(setSpinPosition());

    return true;
}

推荐答案

findViewbyId将尝试从活动的contentView中找到ID.

findViewbyId will try to find the id from the contentView of the activity.

代替

spinnerNumber= (Spinner)findViewById(R.id.numberSpinner);

尝试一下

MenuItem item = menu.findItem(R.id.numberSpinner);
spinnerNumber = (Spinner)item.getActionView()

这篇关于Spinner作为MenuItem未由findViewById初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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