ShareActionProvider is null

我的未来我决定 提交于 2019-12-20 15:37:50

问题


I have been searching for 3 or 4 days about a solution on this. I have tried: Null Pointer exception in using support library share action provider or why MenuItemCompat.getActionProvider returns null? and some others but still I get null on ShareActionProvider. I am pretty new on developing android apps so I really need some help.

My xml menu file is:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_share"
    android:title="@string/action_share"
    app:showAsAction="always"
    android:icon="@android:drawable/ic_menu_share"
    android:actionProviderClass="android.support.v7.widget.ShareActionProvider"/></menu>

and my fragment is:

public static class DailyActivityFragment extends Fragment {
    private static final String LOG_TAG = "Dailyshare";
    private ShareActionProvider mShareActionProvider;

    public DailyActivityFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
        return rootView;
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
        inflater.inflate(R.menu.detailfragment, menu);
        MenuItem item = menu.findItem(R.id.action_share);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
        if (mShareActionProvider != null) {
            mShareActionProvider.setShareIntent(createShareIntent());
        }else{
            Log.i(LOG_TAG, "is null");
        }
    }

    private Intent createShareIntent() {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT,
                "this text will be shared");
        return shareIntent;
    }
}

as an import I have:

import android.support.v7.widget.ShareActionProvider;

回答1:


You could just create a ShareActionProvider and assign it.

mShareActionProvider = new ShareActionProvider();
mShareActionProvider.setShareIntent(createShareIntent())
MenuItemCompat.setActionProvider(item, mShareActionProvider);



回答2:


You have wrong namespace usage in XML:

<menu xmlns:android="http://schemas.android.com/apk/res/android"             xmlns:app="http://schemas.android.com/apk/res-auto">

  <item android:actionProviderClass="android.support.v7.widget.ShareActionProvider"

should be app:actionProviderClass (the provider class is from apk resources, not native android classes).

See https://stackoverflow.com/a/32602896/907576



来源:https://stackoverflow.com/questions/25093706/shareactionprovider-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!