删除共享首选项也会删除默认图像视图



我有一个活动,用户可以上传照片。起初,在他选择照片之前,可绘制文件夹中有一个默认图像。但是,由于我在该视图上有共享的首选项,如果用户返回到以前的活动,我会清除主活动的onDestroy中的共享首选项,然后当我再次启动应用程序时,图像视图为空,而不是显示默认图像。这就是我保存共享偏好的方式:

ActivityTwo.java;

public void onBackPressed() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("imageUri", imageURI);
editor.apply();
super.onBackPressed();
} 

关于主要活动我清理这个偏好:

@Override
public void onDestroy()
{
super.onDestroy();
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
preferences.edit().remove("imageUri").commit();
}

但当我再次启动该应用程序时,ActivityTwo的图像视图只是一个空白的正方形,里面没有默认图像。

那么,我做得对吗?我清除共享偏好的方式?为什么我必须通过主活动的onDestroy而不是活动二来执行?(没用(。以及如何保存默认的图像视图?

这是图像视图的xml:

<ImageView
android:id="@+id/imageView"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="40dp"
android:background="@drawable/image_view_border"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/no_profile_picture" />

检查imageuri是否为null,然后设置image。。。

if(imageURI!=null)
imageView.setImageURI(imageURI)
else imageView.setImageResource(R.drawable.no_profile_picture);

在首先设置默认图像的活动中,检查是否存在自定义图像的首选项,如果存在,则替换图像,如果不存在,则使用默认图像。

例如:

finalUri = imageUri == null? defaultUri : imageUri;
imageView.setImageURI(finalUri);

编辑:要获得可绘制的参考,您可以使用以下代码:

Drawable myImage = getResources().getDrawable(R.drawable.myImage);

最新更新