AndroidViewModel是系统提供的一个类,是ViewMode的一个子类。
这一篇将来介绍下用AndroidViewModel。做一个简单的sp数值保存操作。在我们关掉程序后,重新打开时数值可以重新呈现
因为SharedPreferences是继承Context的一个接口。所以得到对象需要context。
在初始化时,必须将Application上下文作为参数传递。
AndroidViewModel:
public class MyViewModel extends AndroidViewModel {
SavedStateHandle handle;
String key = getApplication().getResources().getString(R.string.data_key);
String spName = getApplication().getResources().getString(R.string.sp_name);
public MyViewModel(@NonNull Application application, SavedStateHandle handle) {
super(application);
this.handle = handle;
if (!handle.contains(key)) {
load();
}
}
public LiveData<Integer> getNumber() {
return handle.getLiveData(key);