elgui
elgui

Reputation: 3323

ActionBar menu inflation error from SherlockFragment (ClassCastException)

I'm trying to use the solution of this post, in order to have a Spinner in my ActionBar. I was first using the NAVIGATION_MODE_LIST of the ActionBar, but I don't want the spinner to be used to navigate trough views (I will have tabs for that). So I've created 2 xml :

mode_spinner.xml

<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

options.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/menu_mode"
    android:actionLayout="@layout/mode_spinner"
    android:showAsAction="ifRoom"/>
</menu>

and then, tried to inflate it from my fragment (SherlockFragment)

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.options, menu);
    Spinner spinner = (Spinner) menu.findItem(R.id.menu_mode);
    spinner.setAdapter(mSpinnerAdapter);
    super.onCreateOptionsMenu(menu, inflater);
}

at runtime, I got this error :

java.lang.ClassCastException: com.actionbarsherlock.internal.view.menu.MenuItemWrapper cannot be cast to android.widget.Spinner

any idea ?

Upvotes: 2

Views: 3594

Answers (1)

Jake Wharton
Jake Wharton

Reputation: 76075

You need to call getActionView() on the resulting item returned from findItem() to access that view. From there you can manipulate it.

You may also want to consider simply using a sub-menu with exclusively checkable items.

Upvotes: 7

Related Questions