看板 KnucklesNote
作者 標題 [AndroidStudio] 加上分享按鈕 Share Action
時間 2016-12-31 Sat. 14:53:46
在右上角選單加上分享功能
![[圖]](http://i.imgur.com/cQTlma0.png)
加上右上角選單的方法參考這篇
[AndroidStudio] Toolbar 使用方法 - KnucklesNote板 - Disp BBS
在選單的 xml 檔加上一個分享按鈕
<item
android:id="@+id/action_share"
android:title="分享"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
不用加上圖示,會自動顯示為android:id="@+id/action_share"
android:title="分享"
app:showAsAction="ifRoom"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />
![[圖]](http://i.imgur.com/LpWVtrA.png)
注意 actionProviderClass 是用 v7 的
在 java 檔加上成員變數
private ShareActionProvider mShareActionProvider;
Import class 要選 appcompat-v7 的![[圖]](http://i.imgur.com/9iYgU4W.png)
![[圖]](http://i.imgur.com/j4biQ8l.png)
修改成員函式 onCreateOptionsMenu(Menu menu)
在 getMenuInflater().inflate(R.menu.menu_text, menu); 之後加上
MenuItem menuItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "要分享的標題");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "要分享的內文");
mShareActionProvider.setShareIntent(shareIntent);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "要分享的標題");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "要分享的內文");
mShareActionProvider.setShareIntent(shareIntent);
執行看看
![[圖]](http://i.imgur.com/cQTlma0.png)
使用 Gmail 分享
![[圖]](http://i.imgur.com/d1a44K5.png)
會抓到標題與內文
使用 Facebook 分享,要分享的內文裡要附上文章網址
![[圖]](http://i.imgur.com/NljM2oA.png)
□ 問題解決記錄
如果照Android Developers 寫的 Adding an Easy Share Action
加上 mShareActionProvider = (ShareActionProvider) item.getActionProvider();
時,執行會出現錯誤
This is not supported, use MenuItemCompat.getActionProvider()
因為是使用 appcompat-v7 的 toolbar,要改用 appcompat-v7 的 ShareActionProvider
參考 StackOverflow
參考
https://guides.codepath.com/android/Sharing-Content-with-Intents
--
※ 作者: Knuckles 時間: 2016-12-31 14:53:46
※ 編輯: Knuckles 時間: 2017-02-25 03:32:14
※ 看板: KnucklesNote 文章推薦值: 0 目前人氣: 0 累積人氣: 427
回列表(←)
分享