SavedStateHandle的使用,临时保存数据

当使用Savedstate保存数据之后,后台进程关闭,数据 也会得到保留
SavedStateHandle的使用,临时保存数据_第1张图片
首先在build.gradle文件中添加一下依赖

android {
        dataBinding.enabled = true
        。。。
    }
    dependencies {
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-rc02'
    。。。
}

然后创建一个类继承ViewModel,在里面有有个SavedStateHandle类型的handle用来保存数据
MyViewModel.java

package com.mrlove.viewmodelsavedstate;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;

public class MyViewModel extends ViewModel {
    private SavedStateHandle handle;

    public MyViewModel(SavedStateHandle handle){
        this.handle = handle;
    }

    public MutableLiveData<Integer> getNumber(){
        if (!handle.contains(MainActivity.KEY_NUMBER)){
            handle.set(MainActivity.KEY_NUMBER,0);  //判断Handle里面的值是否被初始化,如果没有,就赋值这个key的值为0
        }
        return handle.getLiveData(MainActivity.KEY_NUMBER);
    }

    public void add(int n){
        getNumber().setValue(getNumber().getValue()+n);
    }
}

最后在mainactivity中实例化和绑定参数。
Mainactivity.java

package com.mrlove.viewmodelsavedstate;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import com.mrlove.viewmodelsavedstate.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    public final static String KEY_NUMBER = "my_number";
    MyViewModel viewModel;
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(MyViewModel.class);//新的方式获取ViewModel实例
        binding.setData(viewModel);//给前台data绑定数据
        binding.setLifecycleOwner(this);//观察者
    }
}

github参考代码:https://github.com/Mrlove133481/ViewModelSavedState

你可能感兴趣的:(Android)