5.ViewModle

什么是ViewModel

1
2
3
4
它是介于View(视图)和Model(数据模型)之间的一个东西。它起到了桥梁的作用,使视图和数据既能分离,也能保持通信。即ViewModel 
是以生命周期的方式存储与管理UI相关数据。
用于分离 UI 逻辑与 UI 数据。在发生 Configuration Changes 时,它不会被销毁。在界面重建后,方便开发者呈现界面销毁前
的 UI 状态。

ViewModel的特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1.数据持久化
2.异步回调问题,不会造成内存泄漏
3.隔离Model层与View层
4.Fragments间共享数据

ViewModel出现所解决的问题:
1.Activity的具体生命周期管理,每一次反转都是去重新创建了一个Activity
2.Activity的使用,正常onDestory都会清空数据,每次onCreate都会重新加载进来
(手机旋转时,activity会销毁后新建1个activity,viewmodel相当于在做了数据恢复,onCreate数据恢复)

业务目的:
是为了达成数据持久化,去规避Activity在设计当中对于旋转处理造成的实例Activity重置下的数据保存问题
1.ViewModel = Boudle使用!
2.只不过是作了上层的封装!
3.利用了jetpack组件套当中的应用!
4. 在上一个被销毁的Activity与新建的这个Activity之间建立一个Boudle数据传递!

1.依赖库

1
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

2.使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//1.model类
public class DataModel extends ViewModel {
private int age=0;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//2.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_display"
android:gravity="center"
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="40dp"/>
<Button
android:id="@+id/bn_change"
android:onClick="change"
android:text="change"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/bn_rote"
android:onClick="rote"
android:text="rote"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
//3.使用类
public class ViewModelActivity extends AppCompatActivity {
private ActivityViewModelBinding binding;
private DataModel dataModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_view_model);
//不能直接 new DataModel(),这种方式无法自动恢复数据
dataModel = new ViewModelProvider(this).get(DataModel.class);
Log.e("tyl","age="+ dataModel.getAge());
}

public void change(View view) {
dataModel.setAge(dataModel.getAge()+1);
binding.tvDisplay.setText(dataModel.getAge()+"");
}

//旋转后activity销毁后重新onCreate,但是会恢复age在销毁前的值
private Boolean isLand=false;
public void rote(View view) {
setScreenOrientation(isLand);
}
public void setScreenOrientation(boolean isLandScape){
if (isLandScape){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 横屏
}else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 横屏
}
isLand=!isLand;
}
}