代码之家  ›  专栏  ›  技术社区  ›  jxn

编程更改列表首选项选择

  •  0
  • jxn  · 技术社区  · 11 年前

    我已经尝试了这么长时间,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();
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   greenapps    11 年前
     Set<String> locs = preferences.getStringSet("location_preference", null);
    

    没有字符串集 android:key="location_preference" 那里只有一个字符串:

        String location = preferences.getString("location_preference", null;
    

    您必须从预定义数组中获取所有字符串 android:entryValues="@array/locationValues" 并从中随机抽取一个并将其保存到“location_preference”。