当前位置:网站首页>ViewModel 初体验
ViewModel 初体验
2022-07-04 12:51:00 【菜鸟xiaowang】
ViewModel旨在以生命周期意识的方式存储和管理用户界面相关的数据,它可以用来管理Activity和Fragment中的数据.还可以拿来处理Fragment与Fragment之间的通信等等.
基本使用
1.导入依赖
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
2.创建实体对象
public class User implements Serializable {
String name;
int age;
public User(String name,int age){
this.name = name;
this.age = age;
}
}
3.创建 userModel 数据模型
public class UserModel extends ViewModel {
public MutableLiveData<User> mLiveData = new MutableLiveData<>();
public UserModel(){
//初始值
mLiveData.postValue(new User("wang",20));
}
//更新操作
public void doSomething(){
User user = mLiveData.getValue();
user.name = "重新设置的数据";
mLiveData.setValue(user);
}
}
4.activity引用
UserModel userModel = ViewModelProviders.of(this).get(UserModel.class);
userModel.mLiveData.observe(this, new Observer<User>() {
@Override
public void onChanged(User user) {
mMain2Binding.name.setText(user.name);
}
});
public void onClick(View view) {
switch (view.getId()) {
case R.id.updateUser:
userModel.doSomething();
Log.e("tag","onclick");
break;
}
}
5. ViewModel妙用
1: Activity与Fragment"通信"
有了ViewModel,Activity与Fragment可以共享一个ViewModel,因为Fragment是依附在Activity上的,在实例化ViewModel时将该Activity传入ViewModelProviders,它会给你一个该Activity已创建好了的ViewModel,这个Fragment可以方便的访问该ViewModel中的数据.在Activity中修改userModel数据后,该Fragment就能拿到更新后的数据.
public class MyFragment extends Fragment {
public void onStart() {
//这里拿到的ViewModel实例,其实是和Activity中创建的是一个实例
UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
}
}
2: Fragment与Fragment"通信"
下面我们来看一个例子(Google官方例子)
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
model.getSelected().observe(this, { item ->
// Update the UI.
});
}
}
首先定义一个ViewModel,在里面放点数据,然后在MasterFragment和DetailFragment都可以拿到该ViewModel,拿到了该ViewModel就可以拿到里面的数据了,相当于间接通过ViewModel通信了
边栏推荐
- markdown 语法之字体标红
- TestSuite and testrunner in unittest
- Understand chisel language thoroughly 09. Chisel project construction, operation and testing (I) -- build and run chisel project with SBT
- C# wpf 实现截屏框实时截屏功能
- GCC【6】- 编译的4个阶段
- 华昊中天冲刺科创板:年亏2.8亿拟募资15亿 贝达药业是股东
- 国内酒店交易DDD应用与实践——代码篇
- Yingshi Ruida rushes to the scientific and Technological Innovation Board: the annual revenue is 450million and the proposed fund-raising is 979million
- 游戏出海,全球化运营
- Assertion of unittest framework
猜你喜欢
Haobo medical sprint technology innovation board: annual revenue of 260million Yonggang and Shen Zhiqun are the actual controllers
自主工业软件的创新与发展
CVPR 2022 | greatly reduce the manual annotation required for zero sample learning, and propose category semantic embedding rich in visual information (source code download)
【R语言数据科学】:交叉验证再回首
Deming Lee listed on Shenzhen Stock Exchange: the market value is 3.1 billion, which is the husband and wife of Li Hu and Tian Hua
Apple 5g chip research and development failure: continue to rely on Qualcomm, but also worry about being prosecuted?
德明利深交所上市:市值31亿 为李虎与田华夫妻档
Qt如何实现打包,实现EXE分享
MySQL 5 installation and modification free
Ruichengxin micro sprint technology innovation board: annual revenue of 367million, proposed to raise 1.3 billion, Datang Telecom is a shareholder
随机推荐
Understand chisel language thoroughly 11. Chisel project construction, operation and test (III) -- scalatest of chisel test
吃透Chisel语言.04.Chisel基础(一)——信号类型和常量
学内核之三:使用GDB跟踪内核调用链
Golang uses JSON unmarshal number to interface{} number to become float64 type (turn)
markdown 语法之字体标红
吃透Chisel语言.09.Chisel项目构建、运行和测试(一)——用sbt构建Chisel项目并运行
1200. 最小绝对差
Hardware Basics - diode Basics
IP lab monthly resumption · issue 5
R语言使用dplyr包的mutate函数对指定数据列进行标准化处理(使用mean函数和sd函数)并基于分组变量计算标准化后的目标变量的分组均值
IP 实验室月复盘 · 第 5 期
吃透Chisel语言.06.Chisel基础(三)——寄存器和计数器
Install MySQL
Learning projects are self-made, and growth opportunities are self created
Gorm data insertion (transfer)
golang fmt.printf()(转)
[FAQ] Huawei Account Service Error Report 907135701 Common reasons Summary and Solutions
Product identification of intelligent retail cabinet based on paddlex
Mongodb commonly used 28 query statements (forward)
Blob, text geometry or JSON column'xxx'can't have a default value query question