当前位置:网站首页>LiveDatade的基本使用
LiveDatade的基本使用
2022-07-26 20:16:00 【一禅-小和尚】
特征:
1.首先LiveData 其实与数据实体类是一样的东西,它负责暂存数据
2.其次LiveData 其实也是一个观察者模式的数据实体类,它可以跟它注册的观察者回调数据是否已经更新
3.LiveData 还能知晓它绑定的Activity或者Fragment的声明周期,它只会给前台活动的activity回调,这样可以放心的在它的回调方法里直接将数据添加到View,而不用担心会不会报错
LiveData 与MutableLiveData区别:
1.MutableLiveData的父类是LiveData
2.LiveData在实体类里可以通知指定某个字段的数据更新
3.MutableLiveData则是完全是整个实体类或者数据类型变化后才通知,不会细节到某个字段
LiveData不可变,MutableLiveData是可变的
DemoData.java
public class DemoData extends LiveData<DemoData> {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
postValue(this);
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
postValue(this);
}
}
继承LiveData并且在泛型里写下你的实体类,注意的是:postValue(this),这个方法是用于回调数据更新的方法(在需要被观察的数据里添加)
创建ViewModel
需要在ViewModle实例化DemoData这个类(ViewModle是用于管理多个Activity或者Fragment数据的类)
public class DemoViewModel extends ViewModel {
private DemoData data = new DemoData();
public DemoData getData(){
return data;
}
}
在Activity或者Fragment中绑定
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private DemoViewModel mDemoViewModel;
private Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtn = findViewById(R.id.btn);
//获取ViewModel,让ViewModel与此activity绑定
mDemoViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(DemoViewModel.class);
//注册观察者,观察数据的变化
mDemoViewModel.getData().observe(this, new Observer<DemoData>() {
@Override
public void onChanged(DemoData demoData) {
Log.d(TAG, "onChanged: " + demoData.getX());
}
});
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDemoViewModel.getData().setX(10);
}
});
}
}
MutableLiveData
public class MutableLiveData<T> extends LiveData<T> {
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
注意:
postValue
1.此方法可以在其他线程中使用
2.如果在主线程执行发布的任务之前多次调用此方法,则仅将分配最后一个值
3.如果同时调用setValue(a)和postValue(b),一定是值b被a覆盖
setValue:此方法只能在主线里调用
因为MutableLiveData只是作用变量所以我们直接就可以在ViewModel里面实例化它,并且在泛型里标注变量的类型
public class DemoViewModelMutable extends ViewModel {
private MutableLiveData<String> mString = new MutableLiveData<>();
public MutableLiveData<String> getString(){
return mString;
}
public void setString(String s){
mString.setValue(s);
}
}
绑定
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private DemoViewModelMutable mDemoViewModel;
private Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtn = findViewById(R.id.btn);
//获取ViewModel,让ViewModel与此activity绑定
mDemoViewModel = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(DemoViewModelMutable.class);
//注册观察者,观察数据的变化
mDemoViewModel.getString().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
Log.d(TAG, "onChanged: " + s);
}
});
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mDemoViewModel.setString("hahahaha");
}
});
}
}
边栏推荐
- leetcode 链表类
- Kotlin - coroutinecontext
- AI technology, simplifying the complex world | teatalk online application practical series, issue 2
- 每日练习------有一组学员的成绩,将它们按降序排列,要增加一个学员的成绩,将它插入成绩序列,并保持降序
- Buu brush inscription 4
- How to upload and download files
- The UK and Germany have successively launched 5g commercial services, and Huawei has become a behind the scenes hero
- Leetcode array class
- 播报语音 h5 SpeechSynthesisUtterance
- 没有网络怎么配置传奇SF登陆器自动读取列表
猜你喜欢

执行上下文与词法环境

serializable接口的作用是什么?

Houdini 求中点,点连成线

Leetcode linked list problem - 19. Delete the penultimate node of the linked list (learn the linked list with one question and one article)

2022-7-26 第七组 抽象和接口

Message queue -- the problem introduced: repeated consumption & sequential consumption & distributed transactions

Redis interview questions

Redis面试题

Go+mysql+redis+vue3 simple chat room, the sixth bullet: use vue3 and element plus to call the interface

Interceptors
随机推荐
[pytoch foundation] torch.stack() function analysis
Discussion on loan agreement mode with NFT as collateral
hello 你好吗
How to block the legendary GEE engine version? Close player account tutorial through script + engine
Kotlin - coroutinecontext
Go+mysql+redis+vue3 simple chat room, bullet 5: synchronize messages to MySQL using message queues and scheduled tasks
Tkinter uses WPF controls
微信支付的分账功能介绍
Build Prometheus automatic monitoring and alarm system from scratch
Introduction to the billing function of wechat payment
美国应用材料公司宣布将以22亿美元现金收购国际电气
GOM跟GEE登陆器列表文件加密教程
软考 --- 数据库(1)数据库基础
手机\固定电话座机呼叫转移设置方法
[OBS] solve the problem of OBS pushing two RTMP streams + timestamp
Detailed illustration of B-tree and its implementation in C language
Correlation analysis between [machine learning] variables
Buu brush inscription 2
09_ UE4 advanced_ Enter the next level and reserve the blood volume
The UK and Germany have successively launched 5g commercial services, and Huawei has become a behind the scenes hero