[英]Android Q: Load image from file
我從內部存儲加載圖像時遇到問題,我嘗試過以下代碼:
final String imagePath = "/storage/emulated/0/dummy.jpg";
ImageView img = findViewById(R.id.test_image);
if (isStoragePermissionGranted()){
File file = new File(imagePath);
if (file.exists()) {
Log.d("GalleryImages", "file is exist");
Uri uri = Uri.fromFile(file);
img.setImageURI(uri);
}else {
Log.d("GalleryImages", "file is not exist");
}
}
private boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.d("GalleryImages","Permission is granted");
return true;
} else {
Log.d("GalleryImages","Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else {
Log.d("GalleryImages","Permission is granted");
return true;
}
}
和 xml:
<ImageView
android:id="@+id/test_image"
android:scaleType="fitXY"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#63C57878" />
結果是:
D/GalleryImages:已授予權限
D/GalleryImages:文件存在
但 ImageView 上什么也沒有,
我還嘗試使用 Picaso 加載圖像:
Picasso.get().load(file).error(R.mipmap.ic_launcher).into(img);
但也沒有任何工作。
更新
經過太長時間的搜索,我通過添加到 AndroidManifest.xml 上的應用程序在這里找到了解決方案:
android:requestLegacyExternalStorage="true"
希望它會幫助其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.