大家好,大家下午好。
我遇到了一些问题,找不到在sharedPrefernce中保存我的multichoiceDilog所选项目的好方法。
我在论坛上看到了一堆代码,但其中任何一个对我的范围都很有用。
这是我的对话框代码:
private ArrayList mSelectedItems;
private boolean[] itemsChecked = {false, false, false, false};
public void deleteDialog(){
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.deletefiles_title)
.setMultiChoiceItems(R.array.options, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Save here the selected items
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
所以我的问题是,如何用功能存储用户选择?
最终我如何在if语句中使用已检查的项目?
我想到这样的事情:
if(itemsChecked[1]){
deleteDatabases();
}
你觉得伙计们怎么样?你能帮助我吗?
答案 0 :(得分:0)
我编写了一个简单的util类来处理我的共享首选项:
public class SharedPreferencesUtil {
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
static {
sharedPreferences = MBankApplication.appContext.getSharedPreferences(
"sharedPreferenceKey", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public static void saveString(String key, String value) {
editor.putString(key,value);
editor.commit();
}
public static void saveInt(String key, int value) {
editor.putInt(key, value);
editor.commit();
}
public static void saveLong(String key, long value) {
editor.putLong(key, value);
editor.commit();
}
public static void saveBoolean(String key, boolean value) {
editor.putBoolean(key, value);
editor.commit();
}
public static String loadString(String key, String defaultValue) {
return sharedPreferences.getString(key,defaultValue);
}
public static int loadInt(String key, int defaultValue) {
return sharedPreferences.getInt(key, defaultValue);
}
public static long loadLong(String key, long defaultValue) {
return sharedPreferences.getLong(key, defaultValue);
}
public static boolean loadBoolean(String key, boolean defaultValue) {
return sharedPreferences.getBoolean(key, defaultValue);
}
public static void removeString(String key) {
editor.remove(key);
editor.commit();
}
如果您有任何疑问,请与我联系。