问题
I'm having some trouble casting a Menu Item in xml to a Spinner (actionbar compat) . I've tried a couple of options, like these Spinner as MenuItem not initialized by findViewById or Adding spinner to ActionBar (not Navigation , but spinner = (Spinner)item.getActionView(); keeps coming back as null. Setting up a new spinner works though, but that's probably not relevant to my problem.
Code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
//spinner = (Spinner) menu.findItem(R.id.category_spinner).getActionView();
//spinner = new Spinner(this);
MenuItem item = menu.findItem(R.id.category_spinner);
spinner = (Spinner)item.getActionView();
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.operating_systems,android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mSpinnerAdapter);
actionBar.setListNavigationCallbacks(mSpinnerAdapter, mOnNavigationListener);
mOnNavigationListener = new ActionBar.OnNavigationListener() {
String[] strings = getResources().getStringArray(R.array.operating_systems);
@Override
public boolean onNavigationItemSelected(int position, long itemId) {
ListContentFragment newFragment = new ListContentFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, newFragment, strings[position]);
ft.commit();
return true;
}
};
return super.onCreateOptionsMenu(menu);
}
I also tried
MenuItem item = menu.findItem(R.id.category_spinner_item);
spinner = (Spinner) MenuItemCompat.getActionView(item);
http://developer.android.com/guide/topics/ui/actionbar.html#ActionView but also comes back null.
menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/category_spinner"
android:showAsAction="ifRoom"
android:actionLayout="@layout/action_sort" />
<item android:id="@+id/action_share"
android:icon="@drawable/ic_action_share"
android:title="@string/action_share"
yourapp:showAsAction="ifRoom" />
<item android:id="@+id/action_settings"
android:icon="@drawable/ic_action_overflow"
android:title="@string/action_settings"
yourapp:showAsAction="always"/>
</menu>
layout/action_short.xml
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/operating_systems" />
回答1:
getActionView() of my MenuItem return null answers it all:
getActionView() only works if there's a custom actionView from setActionView.
Why though, I have No idea. Why they dont in the example here http://developer.android.com/guide/topics/ui/actionbar.html#ActionView , who knows.
来源:https://stackoverflow.com/questions/22975439/casting-a-menu-item-in-xml-to-a-spinner-actionbar-appcompat