我已经像下面这样设置了 SharedPreferences:
Editor editor = getSharedPreferences("FileName", MODE_PRIVATE).edit();
editor.clear();
editor.putString("chicago", "Chicago, IL");
editor.putString("london", "London, UK");
editor.putString("sanjose", "San Jose, CA");
editor.putString("washington", "Dulles, VA");
editor.commit();
目前我正在从一个数组中填充 AlertDialog,我想使用 SharedPreferences 文件以便我最终可以动态添加项目等。
我现在用来填充的代码是:
private void openServerDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.server_title)
.setItems(R.array.serverchoice,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,
int i) {
setServer(i);
}
})
.show();
}
所以我只想停止使用数组“serverchoice”,而是使用 SharedPreferences 文件中的字符串。
提前致谢
最佳答案
您可以使用 SharedPreferences 对象的 getString() 方法从共享首选项中检索字符串。参见 the documentation for SharedPreferences .
编辑: OP 发表评论后调整答案。
private void openServerDialog() {
SharedPreferences sharedPrefs = getSharedPreferences("FileName", MODE_PRIVATE);
Map<String, ?> sharedPrefsMap = sharedPrefs.getAll();
ArrayList<String> stringArrayList = sharedPrefsMap.values();
CharSequence[] prefsCharSequence = stringArrayList.toArray(new CharSequence[stringArrayList.size()]);
new AlertDialog.Builder(this)
.setTitle(R.string.server_title)
.setItems(prefsCharSequence,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,
int i) {
setServer(i);
}
})
.show();
}
关于android - 我可以使用 sharedPreferences 文件中的项目填充 AlertDialog 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12534258/