我设法在我的 android 应用程序中创建了一个实例变量类,以保存一堆ImageView
. 有没有办法永久保存这个变量SharedPreferences
?即使用户重新启动应用程序,我也需要加载状态。
图像状态
public class ImageState {
//some variables here
public ImageState(Context context, int[] imageId, int space){
//blah blah...
}
public void saveState(){
//saving visibility to shared preferences
}
public void loadState(){
//loading state
}
}
主活动.java
public void save(View view){
//initializing variables here
//creating ImageState
ImageState imageState = new ImageState(this, ids, count);
imageState.saveState();
}
public void load(View view){
if(ImageState!=null) ImageState.loadState();
}
我怎样才能保存imageState
?
您只能持久保存原始数据。整数、字符串可以存储,但上下文不能存储在 SharedPrefs 中。我建议您将所有原语保存在 SharedPreferences 中,然后使用来自 SharedPreferences 的新上下文和数据重新初始化 ImageState。使用此代码在 sharedprefs 中存储数据
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE).edit();
editor.putInt("space", space);
editor.apply();
如果要存储整数数组,请参阅此答案https://stackoverflow.com/a/47120128/4260786
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句