1、viewModel的诞生
- 瞬态数据的丢失
- 异步调用的内存泄露
- 类膨胀提高维护难度和测试难度
2、viewModel的作用
它是介于View(视图)和Model(数据模型)之间的桥梁,使视图和数据能够分离,也能保持通信
3、viewModel的应用
案例:屏幕旋转后用户信息数据仍然存在
4、ViewModel的声明周期的特性
独立于配置变化
不要向ViewModel传入Context,会导致内存的泄露
如果要使用context,请使用AndroidViewMOdel中的Application
5、代码展示
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
style="@style/Widget.AppCompat.TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textAppearance="@style/TextAppearance.AppCompat.Large"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.261"
app:textAllCaps="false" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:onClick="plusNumber"/>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.chenchu.viewmodel;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
MyViewModel viewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
viewModel =new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MyViewModel.class);
textView.setText(String.valueOf(viewModel.number));
}
public void plusNumber(View view) {
textView.setText(String.valueOf(++viewModel.number));
}
}
package com.chenchu.viewmodel;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModel;
public class MyViewModel extends AndroidViewModel {
public int number;
public MyViewModel(@NonNull Application application) {
super(application);
}
}