我有一个共享按钮方法,当我在应用程序启动时单击它时会起作用。它将要求共享显示在activity_main
上的第一张图像,但我不想共享该图像。
[当用户使用相机拍摄照片时,它将覆盖第一张图像,只有在那时我才想共享该照片。
换句话说,我需要某种条件。我想念什么?
activity_main
<ImageView
android:id="@+id/scanned_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="center"
app:srcCompat="@drawable/ic_camera_alt_black_24dp" />
MainActivity
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_share) {
Drawable myDrawable = scannedImageView.getDrawable();
if(myDrawable == null) {
Toast.makeText(MainActivity.this, "Load Image First...", Toast.LENGTH_SHORT).show();
} else {
Bitmap bitmap = ((BitmapDrawable) myDrawable).getBitmap();
try {
Uri file;
File file2 = new File(getExternalCacheDir(), "myImage.png");
FileOutputStream fOut = new FileOutputStream(file2);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
fOut.flush();
fOut.close();
file2.setReadable(true, false);
Intent intentx = new Intent("android.intent.action.SEND");
intentx.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT < 21) {
file = Uri.fromFile(file2);
} else {
StringBuilder sb = new StringBuilder();
sb.append(getPackageName());
sb.append(".provider");
file = FileProvider.getUriForFile(this, sb.toString(), file2);
}
Intent intx = Intent.createChooser(intentx, "Share Image");
for (ResolveInfo resolveInfo : getPackageManager().queryIntentActivities(intx, PackageManager.GET_META_DATA)) {
grantUriPermission(resolveInfo.activityInfo.packageName, file, FLAG_GRANT_READ_URI_PERMISSION);
}
intentx.putExtra("android.intent.extra.STREAM", file);
intentx.setType("image/png");
startActivity(intx);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "File not found", Toast.LENGTH_SHORT).show();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
return super.onOptionsItemSelected(item);
}
1)删除此行app:srcCompat="@drawable/ic_camera_alt_black_24dp"
或从图像视图中不可绘制,最好的方法是使用拍摄的图像创建新字段2)在finally {}