【发布时间】:2020-10-06 03:22:07
【问题描述】:
我在应用重新启动后在图像视图中设置图像时遇到问题。
我正在使用意图从 android 设备获取图像;
// Trigger gallery selection for a photo
public void onPickPhoto() {
// Create intent for picking a photo from the gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
// Bring up gallery to select a photo
startActivityForResult(intent, 0);
}
}
然后我检索图像的 uri 并使用 Picasso 或 setImageURI() 将其设置为图像视图。然后我将 uri 保存在 sharedpreferences 中。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null && resultCode == RESULT_OK) {
switch (requestCode) {
case 0:
// Load the image located at photoUri into selectedImage
photoUri = data.getData();
// Load the selected image into a preview
// Picasso.get().load(photoUri).fit().centerCrop().into(accountImageView);
accountImageView.setImageURI(photoUri);
//Save imageUri in sharedPreferences
imagePreferences = requireActivity().getSharedPreferences(SHAREDIMAGE, Context.MODE_PRIVATE);
editor = imagePreferences.edit();
editor.putString(IMAGEURI, photoUri.toString());
editor.apply();
break;
case 1:
photo = (Bitmap) data.getExtras().get("data");
accountImageView.setImageBitmap(photo);
break;
}
}
}
我正在检索 onstart 中的 uri 以使用,但是虽然当我检查日志时 uri 仍然存在,但 imageview 仍然是空白的
@Override
public void onStart() {
super.onStart();
imagePreferences = requireActivity().getSharedPreferences(SHAREDIMAGE,Context.MODE_PRIVATE);
if(imagePreferences !=null){
String imageUri = imagePreferences.getString(IMAGEURI,null);
if(imageUri !=null){
photoUri = Uri.parse(imageUri);
// Load the selected image into a preview
// Picasso.get().load(photoUri).fit().centerCrop().into(accountImageView);
accountImageView.setImageURI(photoUri);
}
}else {
// Load the selected image into a preview
accountImageView.setImageResource(R.drawable.battlecruiser);
}
我尝试使图像视图无效并检查是否调用了onstart()(并且它总是被调用),但我没有看到任何变化。让我烦恼的是,虽然我已经在我的 drawable 中放置了一张图片以供使用,以防我的 uri 为空,但即使我清除了 sharedpreferences,该图片也从未使用过,并且 imageview 是空白的。
我还应该做什么?
【问题讨论】:
标签: android