ViewModel 简单使用

viewmodel:以注重生命周期的方式管理界面相关的数据,为Activity/Fragment 获得以及保留必要信息

通过下面例子引出viewModel,界面如下,界面中三个控件,最上面是个分数,下面两个按钮分别对分数做+1和+2的操作
ViewModel 简单使用_第1张图片
MainActivity

/**
 * 普通mvc写法实现
 */
public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private Button button1;
    private Button button2;
    private ScoreModel scoreModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        scoreModel = new ScoreModel();
        textView.setText(String.valueOf(scoreModel.getScore()));

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scoreModel.addScore(1);
                textView.setText(String.valueOf(scoreModel.getScore()));
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scoreModel.addScore(2);
                textView.setText(String.valueOf(scoreModel.getScore()));
            }
        });
    }

}


分数ScoreModel 实体类

/**
 * 普通实体类
 */
public class ScoreModel {
    private int score = 0;

    public int getScore() {
        return score;
    }

    public void addScore(int n) {
        this.score += n;
    }
}

布局文件activity_main.xml

<?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/textView"
        android:layout_width="wrap_content"
        android:layout_height="32dp"
        android:text="0"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.21" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.461" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="+1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.32" />
</androidx.constraintlayout.widget.ConstraintLayout>

运行效果如下
ViewModel 简单使用_第2张图片
app切换到后台,当内存吃紧、手机为了省电杀掉进程、用户手动手改手机配置(如手机语言)或者app设置,再打开app,这时候之前计算的分数就变成0了;效果如下

ViewModel 简单使用_第3张图片
之前做界面数据缓存都是在onSaveInstanceState方法中保存,并在onRestoreInstanceState方法或者onCreate方法中进行对bundle判断,有值则回显;有了viewmodel后,就简单多了

新增MyMainModel类继承ViewModel替换刚才的ScoreModel ,代码如下

/**
 * ViewModel测试类
 */
public class MainViewModel1 extends ViewModel {
    private int score = 0;

    public int getScore() {
        return score;
    }

    public void addScore(int n) {
        this.score += n;
    }
}


添加依赖

implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'

改后的MainActivity,其他不变

/**
 * ViewModel测试类
 */
public class MainActivity1 extends AppCompatActivity {

    private TextView textView;
    private Button button1;
    private Button button2;
    private MainViewModel1 viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        viewModel = ViewModelProviders.of(this).get(MainViewModel1.class);//新版写法可能不同
        textView.setText(String.valueOf(viewModel.getScore()));

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.addScore(1);
                textView.setText(String.valueOf(viewModel.getScore()));
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.addScore(2);
                textView.setText(String.valueOf(viewModel.getScore()));
            }
        });
    }

}


运行效果和之前一样,现在尝试下切换系统语言,发现界面数据不会丢失了,因为viewodel帮我们做了处理

ViewModel 简单使用_第4张图片

仅此记录,如有问题欢迎指出,谢谢

你可能感兴趣的:(android,android,ViewModel)