Android support library v7, can't get ActionProvider

1.7k views Asked by At

I have custom ActionProvider like this.

....
import android.support.v4.view.ActionProvider;

public class MyActionProvider extends ActionProvider {
    ....
}

And in menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
    <item android:id="@+id/example_action_provider"
    yourapp:showAsAction="ifRoom"
    android:title="More"
    android:icon="@drawable/abc_ic_menu_moreoverflow_normal_holo_light"
    yourapp:actionProviderClass="com.example.MyActionProvider" />
</menu>

I'm trying to get ActionProvider with this code:

import android.support.v4.view.ActionProvider;

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu, menu);
    MenuItem menuItem = menu.findItem(R.id.example_action_provider);
    Object hack = menuItem.getActionProvider();
    ActionProvider actionProvider = (ActionProvider)hack;
    super.onCreateOptionsMenu(menu, inflater);
}

menuItem.getActionProvider returns android.support.v7.internal.view.menu.MenuItemWrapperJB$ActionProviderWrapperJB type of object. And it cannot be cast to android.support.v4.view.ActionProvider. Since MyActionProvider gets some clicked events, it needs to tell back to the fragment or activity. How to handle this situation?

1

There are 1 answers

0
ianhanniballake On BEST ANSWER

You have to use MenuItemCompat.getActionProvider(MenuItem) to retrieve the ActionProvider as seen in the examples on the Adding an Action Provider guide.