Android >> 19. AndroidViewModel

Android >> 19. AndroidViewModel_第1张图片

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,安卓开发)