Android(安卓)>> 19. AndroidViewModel
16lz
2022-03-20
> 19. AndroidViewModel_第1张图片" width="650" height="629" style="border:1px solid black;">
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); }}
更多相关文章
- Read Contacts information in Android(安卓)system.
- Android实用代码片段(一)
- Android(安卓)获取本机WIFI及3G网络IP
- android将后台应用置顶及moveTaskToFront的用法
- Android:获取屏幕完整宽高,包含状态栏
- android设置gps自动开启
- android > 获取图片 从 本地 /相机
- [CSDN]Android应用程序启动过程源代码分析
- Android(安卓)adb shell后面可用的常用命令详细列举