【发布时间】:2014-11-26 22:22:33
【问题描述】:
我想在共享首选项中存储一个布尔数组,并且我想稍后访问数组元素。任何人都可以帮助我吗?谢谢advnc。
【问题讨论】:
-
关于这个还有一个问题:stackoverflow.com/questions/3876680/…
我想在共享首选项中存储一个布尔数组,并且我想稍后访问数组元素。任何人都可以帮助我吗?谢谢advnc。
【问题讨论】:
存储你的数组
public boolean storeArray(Boolean[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putBoolean(arrayName + "_" + i, array[i]);
return editor.commit();
}
加载你的数组
public Boolean[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
Boolean array[] = new Boolean[size];
for(int i=0;i<size;i++)
array[i] = prefs.getBoolean(arrayName + "_" + i, false);
return array;
}
【讨论】:
存储您的数组全局设置复选框值
public boolean setCheckboxarray(Context mContext,Boolean[] array) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(CHECKBOXARRAY, array.length);
for(int i=0;i<array.length;i++)
editor.putBoolean(CHECKBOXARRAY + i, array[i]);
return editor.commit();
}
全局加载你的数组获取复选框值
public Boolean[] getCheckboxarray(Context mContext) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
int size = prefs.getInt(CHECKBOXARRAY, 0);
Boolean array[] = new Boolean[size];
for(int i=0;i<size;i++)
array[i] = prefs.getBoolean(CHECKBOXARRAY+ i, false);
return array;
}
【讨论】:
使用复选框将 ArrayList 全局存储在 sharedpreferences 中。
public boolean saveCheckboxarray(Context mContext, ArrayList<Boolean> array) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(CHECKBOXARRAY, array.size());
for(int i=0;i<array.size();i++)
editor.putBoolean(CHECKBOXARRAY + i,array.get(i));
return editor.commit();
}
在 sharedpreferences 状态下全局加载 ArrayList。
public ArrayList<Boolean> getCheckboxarray(Context mContext) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
int size = prefs.getInt(CHECKBOXARRAY, 0);
ArrayList<Boolean> getArray=new ArrayList<Boolean>();
for(int i=0;i<size;i++)
getArray.add(i,prefs.getBoolean(CHECKBOXARRAY + i, false));
return getArray;
}
【讨论】: