问题
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