ViewModel 简单使用

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

通过下面例子引出viewModel,界面如下,界面中三个控件,最上面是个分数,下面两个按钮分别对分数做+1和+2的操作
在这里插入图片描述
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>

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

在这里插入图片描述
之前做界面数据缓存都是在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帮我们做了处理

在这里插入图片描述

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

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值