我已经尝试了这么长时间,top试图找出如何在没有用户实际操作的情况下更改列表首选项中的选择。我需要做的是使用一个方法,随机选择列表首选项的其中一个选项。只有选中“随机化”复选框时,才能执行此操作。这一部分我可以正常工作,但实际的随机化不起作用。以下是我所拥有的:
以下是列表首选项
<ListPreference
android:key="location_preference"
android:title="@string/location"
android:summary="@string/location_summary"
android:entries="@array/locations"
android:entryValues="@array/locationValues"
android:defaultValue="Canyon"
android:dialogTitle="@string/location" />
这是我想出的随机化选择的方法
protected static void setRandomLocation(Context context){
SharedPreferences preferences = getPreferences(context);
Set<String> locs = preferences.getStringSet("location_preference", null);
int idx = new Random().nextInt(locs.toArray().length);
String random = (String) (locs.toArray()[idx]);
preferences.edit().putString("location_preference", random);
preferences.edit().commit();
}
private static SharedPreferences getPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
我做错了什么/应该怎么做?
编辑:所以我尝试了以下方法来修复它,但没有成功。
protected static void setRandomLocation(Context context){
Resources res = context.getResources();
SharedPreferences preferences = getPreferences(context);
String curr = preferences.getString("location_preference", null);
int idx = new Random().nextInt(res.getStringArray(R.array.locationValues).length);
String random = (String) (res.getStringArray(R.array.locationValues)[idx]);
if(random == curr)
setRandomLocation(context);
preferences.edit().putString("location_preference", random);
preferences.edit().commit();
}