下面的代码用于从 SharedPreferences 文件填充 AlertDialog 并按值按字母顺序对其进行排序。
当用户单击 AlertDialog 列表中的选项时,它会启动
setServer(prefsCharSequence[i]);
prefsCharSequence[i] 返回所选选项的值。
我想为那个值使用“键”。给定我当前的代码,我该如何获得这个?现在我知道我希望它是一个简单的“prefsCharSequence[i].getKey()”或类似的值。
public void openServerDialog() {
final SharedPreferences myPrefs = this.getSharedPreferences("FileName", MODE_PRIVATE);
TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Log.i("map values", entry.getKey());
//some code
}
List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
sortedByValue.add(e);
}
// Pair doesn't have a comparator, so you're going to need to write one.
Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {
String sls = String.valueOf(lhs.first);
String srs = String.valueOf(rhs.first);
int res = sls.compareTo(srs);
// Sort on value first, key second
return res == 0 ? lhs.second.compareTo(rhs.second) : res;
}
});
for (Pair<Object, String> pair : sortedByValue) {
Log.i("map values", pair.first + "/" + pair.second);
}
Collection<?> stringArrayList = keys.values();
final 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(prefsCharSequence[i]);
}
})
.show();
}
我正在尝试迭代并获取我拥有的价值的关键,到目前为止我有这个但不知道下一步该去哪里:
CharSequence server = i;
SharedPreferences myPrefs = this.getSharedPreferences("FileName", MODE_PRIVATE);
Map<String, ?> items = myPrefs.getAll();
for(String s : items.keySet()){
}
i 等于我想要的键的值,这个方向是否正确?