【问题标题】:How to livedata in Imageview src?如何在 Imageview src 中保存数据?
【发布时间】:2020-07-03 15:09:01
【问题描述】:

我的视图模型:

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是正常的,但是每次回老家都运行这个方法,所以觉得很浪费内存,所以打算改成绑定live data。

【问题讨论】:

    标签: android kotlin mvvm imageview android-livedata


    【解决方案1】:

    改用LiveData&lt;Drawable&gt;

        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 }" />
    

    【讨论】:

    • @LeeDuSeop 随便你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多