Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why MenuItemCompat.getActionProvider returns null?

Tags:

java

android

I tried to use android.support.v7.widget.ShareActionProvider on actionbar in my app. So I followed the example from android document but got some issues.
Here's my menu xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myapp="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/action_share"
        android:orderInCategory="100"
        android:icon="@drawable/ic_action_share"
        android:title="@string/action_share"
        myapp:showAsAction="ifRoom"
        myapp:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

</menu>

here's my code to create the share action button:

@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.share, menu);
    MenuItem shareItem = menu.findItem(R.id.action_share);
    ShareActionProvider mShareActionProvider = (ShareActionProvider)MenuItemCompat.getActionProvider(shareItem);
    mShareActionProvider.setShareIntent(getDefaultIntent());
    super.onCreateOptionsMenu(menu, inflater);
}

My question is:

  1. MenuItemCompat.getActionProvider(shareItem) always returns null for me, why's that?
  2. When I comment those lines, the share button appears on the bar but does nothing while clicking, how to fix it(if question 1 can't be solved)?

btw, I checked codes of MenuItemCompat.getActionProvider, it looks like this method will check if the menu item implements SupportMenuItem interface and returns fail if it isn't. How could I deal with it?

like image 592
hago Avatar asked Sep 10 '25 05:09

hago


1 Answers

In my case it was wrong namespace in menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/menu_item_share"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>

Pay attention to app:actionProviderClass="android.support.v7.widget.ShareActionProvider": it should have

  • correct package (android.widget android.support.v7.widget)
  • correct namespace (android app).

Unfortunatelly, the compiler compiles it without errors, only Android Studio makes notification with underlining.

like image 109
radistao Avatar answered Sep 12 '25 18:09

radistao