實作效果:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5yMwMjZmRGM2EWOzUmMykTYkVWM2AjNkRWOkVjZxE2Yi9CX0JXZ252bj91Ztl2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
實作過程:
首先定義以下數組:
//長按後顯示的 Item
final String[] items = new String[] { "儲存圖檔"};
//圖檔轉成Bitmap數組
final Bitmap[] bitmap = new Bitmap[1];
圖檔轉Bitmap數組代碼:
Glide.with(context).load(url).asBitmap().into(new SimpleTarget() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation super Bitmap> glideAnimation) {
bitmap[0] = resource;
}
});
給view設定長按監聽事件:
icon.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
//彈出的“儲存圖檔”的Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
if(bitmap[0] !=null){
saveImageToGallery(context, bitmap[0]);
}else {
ToastUtils.showShort(context,"bitmap為空");
}
}
}
});
builder.show();
return true;
}
儲存圖檔的方法:
public static void saveImageToGallery(Context context, Bitmap bmp) {
// 首先儲存圖檔 建立檔案夾
File appDir = new File(Environment.getExternalStorageDirectory(), "shy");
if (!appDir.exists()) {
appDir.mkdir();
}
//圖檔檔案名稱
String fileName = "shy_"+System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("111",e.getMessage());
e.printStackTrace();
}
// 其次把檔案插入到系統圖庫
String path = file.getAbsolutePath();
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
} catch (FileNotFoundException e) {
Log.e("333",e.getMessage());
e.printStackTrace();
}
// 最後通知圖庫更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
ToastUtils.showShort(context,"儲存成功");
}