如何在Imageview src中保存数据?

问题描述 投票:1回答:1

我的视图模型:

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。

按恢复正常操作是正常的,但是每次我回到家中时,都会运行此方法,因此我认为这是浪费内存,因此我将其更改为绑定实时数据。

android kotlin mvvm imageview android-livedata
1个回答
0
投票
改为使用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 }" />

© www.soinside.com 2019 - 2024. All rights reserved.