Android Studio 之 LiveData 的配合使用,底层数据变化,自动通知界面
viewModelWithLikeData.getLikeNumber().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
textView.setText(String.valueOf(integer));
}
});
通过 ViewModel 对象方法的 observe onChanged事件,自动对界面上的控件,进行数据更新
1.ViewModel类
创建 对象 MutableLiveData<Integer> likeNumber
创建 这个对象的 GET 、 SET 方法
package com.example.livedatatest;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class ViewModelWithLikeData extends ViewModel {
private MutableLiveData<Integer> likeNumber;
//用构造函数,防止访问到的内容是空的,不能这样用,不知道为什么,会出错
/*
ViewModelWithLikeData(){
likeNumber = new MutableLiveData<>();
likeNumber.setValue(0);
}
*/
public MutableLiveData<Integer> getLikeNumber() {
if(likeNumber==null) {
likeNumber = new MutableLiveData<>();
likeNumber.setValue(0);
}
return likeNumber;
}
public void setLikeNumber(MutableLiveData<Integer> likeNumber) {
this.likeNumber = likeNumber;
}
public void addLikeNumber(int n) {
likeNumber.setValue(likeNumber.getValue()+n);
}
}
2. Activity 类
创建 ViewModel 对象,实例化对象
对 ViewModel 对象的 observe onChanged 事件进行监控,如有变化,就自动给控件赋值!
package com.example.livedatatest;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
public class MainActivity extends AppCompatActivity {
ViewModelWithLikeData viewModelWithLikeData;
TextView textView;
ImageButton imageButton1;
ImageButton imageButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
imageButton1 = findViewById(R.id.imageButton);
imageButton2 = findViewById(R.id.imageButton2 );
//注意: ViewModelProviders 必须在 build.gradle 中引入如下语句,否则导入不了类
//implementation ‘androidx.lifecycle:lifecycle-extensions:2.1.0‘
viewModelWithLikeData = ViewModelProviders.of(this).get(ViewModelWithLikeData.class);
//设置一个监听器,当这个值有变化时,自动给控件赋值。
viewModelWithLikeData.getLikeNumber().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
textView.setText(String.valueOf(integer));
}
});
imageButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
viewModelWithLikeData.addLikeNumber(1); //点赞加1
}
});
imageButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
viewModelWithLikeData.addLikeNumber(-1); //踩-1
}
});
}
}
Android Studio 之 LiveData 的配合使用,底层数据变化,自动通知界面
原文:https://www.cnblogs.com/gfwei/p/11779342.html