Android >> 19. AndroidViewModel
16lz
2021-01-23
public class MyViewModel extends AndroidViewModel { private SavedStateHandle handle; /* 获取应用资源,以提供此类访问权限 */ private String key = getApplication().getResources().getString(R.string.Key); private String shp_name = getApplication().getResources().getString(R.string.shp_name); public MyViewModel(@NonNull Application application, SavedStateHandle handle) { super(application); this.handle = handle; if (!handle.contains(key)) { load(); } } private LiveData<Integer> getNumber() { return handle.getLiveData(key); } private void load() { SharedPreferences shp = getApplication().getSharedPreferences(shp_name, Context.MODE_PRIVATE); int x = shp.getInt(key, 0); handle.set(key, x); } void save() { SharedPreferences shp = getApplication().getSharedPreferences(shp_name, Context.MODE_PRIVATE); SharedPreferences.Editor editor = shp.edit(); editor.putInt(key, (getNumber().getValue() == null ? 0 : getNumber().getValue())); editor.apply(); } void add(int x) { handle.set(key, (getNumber().getValue() == null ? 0 : getNumber().getValue()) + x); }}
更多相关文章
- android项目colors.xml中几个常用的颜色资源
- Android资源目录
- Android ListView异步加载网络图片
- Android使用HttpURLConnection显示网络图片
- Android资源文件mk的格式
- android 加载 网络图片
- Android 拖拽图片