Spinner as MenuItem not initialized by findViewById

▼魔方 西西 提交于 2019-12-22 10:32:54

问题


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:

<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

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

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

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

回答1:


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

Instead of

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

Try this

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


来源:https://stackoverflow.com/questions/12272104/spinner-as-menuitem-not-initialized-by-findviewbyid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!