android - 在 Android Studio 中使用 ListPreference

标签 android android-activity android-studio android-preferences

我有一个设置菜单,其中包含来自 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" />

在此列表首选项中,您可以选择 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

等等

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

最佳答案

<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!");
}

关于android - 在 Android Studio 中使用 ListPreference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798370/

相关文章:

android - 主线程使用

android - 等待并发 GC 阻塞

android - 如何从 CalendarView 获取星期几

android - 退出安卓应用

java - Android Studio v3.1.1 中的构建错误

android - CPU 处理相机图像

android - 从 surfaceview 访问 Android sharedPreferences

java - 如果一个 Activity 实现了回调并且该引用被传递给另一个线程中的网络调用并且屏幕被旋转,这是否是内存泄漏?

java - 导入 NotNull 或 Nullable 并且 Android Studio 不会编译

java - Android 登录屏幕无法正常工作