首页 > 解决方案 > 如何在 Imageview src 中保存数据?

问题描述

我的视图模型:

init{
  updateWallPaper()
}

private var _wallpaper = MutableLiveData<Bitmap>()
    val wallpaper: LiveData<Bitmap>
        get() = _wallpaper
fun updateWallPaper() {
        val file = appCtx.getWallpaperFile()
        if(file.exists()) {
            _wallpaper.value = BitmapFactory.decodeFile(file.absolutePath)
        }
    }

和我的家Activity.xml

<ImageView
            android:id="@+id/imageview_main_home_img"
            android:layout_width="match_parent"
            android:layout_height="324dp"
            android:scaleType="fitXY"
            android:src="@drawable/sample_image"
            app:layout_constraintTop_toTopOf="parent"
            app:load="@{homeViewModel.wallpaper }" />

我要做的就是把这张图片换到别的地方,图片src会实时变化。

我尝试了很多方法但都失败了,我想知道如何将实时数据应用于 src。

操作onresume是正常的,但是每次回到家都运行这个方法,所以觉得很浪费内存,所以打算改成绑定活数据。

标签: androidkotlinmvvmimageviewandroid-livedata

解决方案


改用LiveData<Drawable>

    private var _wallpaper = MutableLiveData<Drawable>()
    val wallpaper: LiveData<Drawable>
        get() = _wallpaper

    fun updateWallPaper() {
        val file = appCtx.getWallpaperFile()
        if(file.exists()) {
            _wallpaper.value = BitmapDrawable(resources, BitmapFactory.decodeFile(file.absolutePath))
        }
    }

然后您可以使用ImageView.setImageDrawable(Drawable)数据绑定 XML(通过使用app:imageDrawable语法):

<ImageView
            android:id="@+id/imageview_main_home_img"
            android:layout_width="match_parent"
            android:layout_height="324dp"
            android:scaleType="fitXY"
            android:src="@drawable/sample_image"
            app:layout_constraintTop_toTopOf="parent"
            app:imageDrawable="@{homeViewModel.wallpaper }" />

推荐阅读