Eri*_*man 6 android menu shareactionprovider
我如何获得ShareActionProvider菜单项的onClick事件?
我的应用程序在库中显示一些图像(带有imageView的片段),我需要获取onClick事件以从缓存加载当前图像,生成临时文件并共享它.
我的分享按钮:
<item android:id="@+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="@string/menu_share"
android:actionProviderClass="android.widget.ShareActionProvider" />
Run Code Online (Sandbox Code Playgroud)
我试过了:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.manage_keywords:
startActivity(new Intent(this, KeywordActivity.class));
return true;
case R.id.menu_item_share:
/*it should handle share option*/
return true;
}
return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)
和
menuShare = menu.findItem(R.id.menu_item_share);
menuShare.setOnActionExpandListener(new OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
还有其他建议吗?谢谢!
每次用户单击ShareActionProvider时,将要共享的图像保存到SDCard,完整示例:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
ShareActionProvider shareActionProvider = (ShareActionProvider) menu.findItem(R.id.shareactionprovider).getActionProvider();
shareActionProvider.setShareIntent(getShareIntent());
shareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
@Override
public boolean onShareTargetSelected(ShareActionProvider actionProvider, Intent intent) {
saveImageToSD();
return false;
}
});
return true;
}
private Intent getShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
File sdCard = Environment.getExternalStorageDirectory();
File sharedFile = new File(sdCard+"/yourPath/yourImage.jpg");
Uri uri = Uri.fromFile(sharedFile);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
return shareIntent;
}
private void saveImageToSD() {
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.yourimage);
OutputStream outStream = null;
try {
outStream = new FileOutputStream(getTempFile());
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
bm.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File directory = new File(Environment.getExternalStorageDirectory() + "/yourPath/");
directory.mkdirs();
File file = new File(directory ,"yourImage.jpg");
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)