gpt4 book ai didi

android - 如何在 Imageview src 中保存数据?

转载 作者:行者123 更新时间:2023-12-02 13:43:57 24 4
gpt4 key购买 nike

我的 View 模型:

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是正常的,但是每次回到家都会运行这个方法,所以觉得很浪费内存,所以打算改成绑定(bind)活数据。

最佳答案

使用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)来自数据绑定(bind) 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 }" />

关于android - 如何在 Imageview src 中保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60808732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com