ShareActionProvider为null

时间:2014-08-02 09:46:26

标签: android nullpointerexception shareactionprovider

我一直在寻找解决方案3到4天。我试过了: Null Pointer exception in using support library share action provider 要么 why MenuItemCompat.getActionProvider returns null?和其他一些人 但我仍然在ShareActionProvider上得到null。我是开发Android应用程序的新手,所以我真的需要一些帮助。

我的xml菜单文件是:

<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>

我的片段是:

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;
    }
}

作为导入我:

import android.support.v7.widget.ShareActionProvider;

2 个答案:

答案 0 :(得分:15)

您可以创建一个ShareActionProvider并分配它。

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

答案 1 :(得分:12)

您在XML中使用了错误的命名空间:

  

&lt; menu xmlns: android =“http://schemas.android.com/apk/res/android”     的xmlns:应用 = “http://schemas.android.com/apk/res-auto” &GT;

     

&lt; item android :actionProviderClass =“android.support.v7.widget.ShareActionProvider”

应该是 app :actionProviderClass (提供者类来自apk资源,而不是原生的Android类)。

请参阅https://stackoverflow.com/a/32602896/907576