我在使用ShareActionProvider时遇到一个奇怪的问题。
每件事都正确链接。共享按钮在那里,但不起作用。我确实在logcat上看到一个事件,但是在电话上什么都没有发生。
menu.xml
<xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/action_share"
android:title="@string/action_share"
app:showAsAction="always"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
/>
片段菜单初始化代码
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
public DetailsFragment() {
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailsfragment_menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set the share intent now.
if (YOUTUBE_KEY != null) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
}
}
//分享意图代码
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
Uri videoLocation = Uri.parse(YOUTUBE_API).buildUpon()
.appendQueryParameter("v", YOUTUBE_KEY)
.build();
shareIntent.putExtra(Intent.EXTRA_TEXT, MOVIES_SHARE_HASHTAG);
shareIntent.setData(videoLocation);
return shareIntent;
}
最佳答案
使用ShareActionProvider时,需要在初始化后立即设置内容,因此请在您内部的onCreateOptionMenu上进行设置以共享虚拟内容,并在初始化后将ShareProvider的引用获取到全局ShareActionProvider对象中,即globalShareActionProvider
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detailfragment, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent
ShareActionProvider mShareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent ot this ShareActionProvider.
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(createShareForecastIntent());
globalShareActionProvider=mShareActionProvider;
} else {
Log.d(LOG_TAG, "Share Action Provider is null?");
}
}
之后,调用setShareIntent创建具有更新值的新意图
就像我在onLoaderFinish函数中使用它一样
shareActionString= String.format("%s - %s - %s/%s",
mdateView.getText(), mNewShareContent, hour, minutes);
globalShareActionProvider.setShareIntent(createShareForecastIntent());
我的createShareForecastIntent()
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, shareActionString
+ SHARE_HASHTAG);
return shareIntent;
}