我一直在寻找有关此解决方案的 3 或 4 天。我尝试过: 使用支持库共享操作提供程序时出现空指针异常 或 为什么 MenuItemCompat.getActionProvider 返回空值?和其他一些,但我仍然在 ShareActionProvider 上得到空值。我对开发 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;