【问题标题】:Using ListPreference in AndroidStudio在 Android Studio 中使用 ListPreference
【发布时间】:2015-05-02 03:08:15
【问题描述】:

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

 <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

等等

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

【问题讨论】:

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


    【解决方案1】:

    &lt;string-array name="pref_example_list_values"&gt; 将用作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!");
    }
    

    【讨论】:

    • 感谢您的回答。另一个问题,有没有办法在文本中显示值,例如:“Welcome, (value here)!”
    • 我的回答有误,请重新检查。要在TextView 中设置值,您可以对每个值一一进行。哦,如果这个答案对你有帮助,请采纳。
    • 感谢您的回答。当我尝试插入代码时,getValue 被标记为红色,并且 findPreference 显示为已弃用。这是有原因的吗?
    • 我不知道它显示为已弃用的原因,但它仍然对我有用。
    【解决方案2】:

    你可以像这样得到你的偏好值:

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

    我不明白你的其余问题。是什么

    如何将值分配给链接并将它们放在一个变量中,当偏好发生变化时该变量会发生变化? 什么意思?

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

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 2012-06-02
      • 1970-01-01
      • 2011-04-05
      相关资源
      最近更新 更多