android MutableLiveData 赋值

Android开发中,MutableLiveData是一个用于管理可观察型数据的类,它是LiveData的一个子类,可以用来传递数据给UI层。

要给MutableLiveData赋值,你需要调用它的setValue(T)方法或者postValue(T)方法。

1、声明代码:

复制代码
class HomeViewModel : ViewModel() {

    private val _text = MutableLiveData<String>().apply {
        value = "This is home Fragment"
    }
    val text: LiveData<String> = _text

    fun setText(value: String) {
        _text.value = value;
    }

    fun postText(value:String){
        _text.postValue(value);
    }

}

2、调用方法:

复制代码
val homeViewModel =
            ViewModelProvider(this).get(HomeViewModel::class.java)

homeViewModel.setText("hello,world")
homeViewModel.postText("hello")

创建ViewModel提供程序。这将创建ViewModel并将其保留在给定ViewModel StoreOwner的存储中,这样我们就可以用homeViewModel来调用方法了。

说明:

setValue应该只在主线程中使用,而postValue可以在任何线程中使用。在实际应用中,如果你需要在后台线程中更新数据,你应该使用postValue。

相关推荐
书弋江山12 分钟前
flutter 跨平台编码库 protobuf 工具使用
android·flutter
来来走走3 小时前
Flutter开发 webview_flutter的基本使用
android·flutter
Jerry说前后端3 小时前
Android 组件封装实践:从解耦到架构演进
android·前端·架构
louisgeek4 小时前
Android OkHttp Interceptor
android
大王派来巡山的小旋风4 小时前
Kotlin基本用法三
android·kotlin
Jerry说前后端5 小时前
Android 移动端 UI 设计:前端常用设计原则总结
android·前端·ui
bytebeats5 小时前
Jetpack Compose 1.9: 核心新特性简介
android·android jetpack
Icey_World5 小时前
Mysql笔记-错误条件\处理程序
android
大王派来巡山的小旋风6 小时前
Kotlin基本用法之集合(一)
android·程序员·kotlin
用户2018792831676 小时前
智能广播系统(RemoteCallbackList)的诞生
android