在 Android Studio 中使用 ListPreference

Using ListPreference in AndroidStudio

我有一个设置菜单,其中包含来自 Android Studio 中示例设置 activity 的列表首选项。

 <ListPreference
    android:key="example_list"
    android:title="@string/pref_title_add_friends_to_messages"
    android:defaultValue="5"
    android:entries="@array/pref_example_list_titles"
    android:entryValues="@array/pref_example_list_values"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null" />

在此列表首选项中,您可以 select 8 个不同的选项。

  <string name="pref_title_add_friends_to_messages">Klasse</string>
<string-array name="pref_example_list_titles">
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</string-array>
<string-array name="pref_example_list_values">
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</string-array>

我想使用首选项的值来显示属于 8 个不同设置的链接。

例如:

5 - google.com

6 - wikipedia.com

等等

作为初学者,我如何获得我的偏好值以及如何将值分配给链接并将它们放入一个变量中,该变量会随着偏好的变化而变化?

您可以像这样获取您的偏好值:

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String value = sharedPref.getString("example_list", "default value");

我不明白你剩下的问题。

是什么意思

how do assign the values to the links and put them in one variable, which changes when the preference is being changed? mean?

此外,我发现 the documentation 偏好设置非常有用。

<string-array name="pref_example_list_values"> 将用作 ListPreference 中的值。要获取当前值,请使用:

ListPreference lp = (ListPreference) findPreference("example_list");
String currentValue = lp.getValue();

要获取值并将其显示在文本中,请使用 TextView 并设置文本:

/* You might create 'if' statement for 8 times because of there are 8 different value in the ListPreference*/

TextView tv = (TextView) findViewById(R.id.textview1);

if (currentValue.equals("5")) {
// do your thing here, i.e. google.com
tv.setText("Welcome, 5!");
}
if (currentValue.equals("6")) {
// do your thing here, i.e. wikipedia.com
tv.setText("Welcome, 6!");
}