【问题标题】:Removing shared preferences also removes default image view删除共享首选项也会删除默认图像视图
【发布时间】:2018-11-26 20:58:04
【问题描述】:

我有一个用户可以上传照片的活动。起初,在他选择照片之前,可绘制文件夹中有一个默认图像。但是,由于我在该视图上共享了首选项,以防用户返回之前的活动,我在主活动的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 而不是 ActivityTwo?(它不起作用)。以及如何保存默认图像视图?

这是图像视图的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" />

【问题讨论】:

  • 你能告诉我你加载图像的代码吗?
  • 发布您的 xml 或显示您如何设置默认图像可绘制
  • 添加了xml,谢谢
  • 为什么要将 ImgUri 存储到共享首选项中?
  • 你想完成什么?

标签: android


【解决方案1】:

检查 imageuri 是否为空,然后设置 image...

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

【讨论】:

    【解决方案2】:

    在你设置默认图片的Activity上,检查是否有自定义图片的偏好,如果有,替换图片,如果没有,使用默认。

    例如:

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

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

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

    【讨论】:

    • 但默认图像在使用xml的drawable文件夹中
    • 你可以像这样得到一个drawable的引用:Drawable myImage = getResources().getDrawable(R.drawable.myImage);
    • 但是 defaultUri 应该是 Drawable 类型,不是吗?那么如果你写defaultUri,它怎么能工作呢?
    • 在这里查看如何从 drawable 中获取 Uri:stackoverflow.com/questions/19566840/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多