如何在 Imageview src 中获取 livedata?

How to livedata in 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操作是正常的,但是每次return到家,这个方法都会运行,所以我觉得很浪费内存,所以我准备改成绑定直播数据。

改用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))
        }
    }

然后您可以使用来自数据绑定 XML 的 ImageView.setImageDrawable(Drawable)(通过使用 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 }" />