ListPreference 依赖项

ListPreference dependency(ListPreference 依赖项)

本文介绍了ListPreference 依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListPreference,看起来像这样:

I have a ListPreference which look something like this:

<ListPreference
android:title="Choose item"
android:summary="..."
android:key="itemList"
android:defaultValue="item1"
android:entries="@array/items"
android:entryValues="@array/itemValues" />

然后,我有另一个偏好,只有在 ListPreference 中选择了item3"时才应该启用它.

Then, I have another preference which should only be enabled if "item3" is selected in the ListPreference.

我可以通过 android:dependency 以某种方式完成此任务吗?类似 android:dependency="itemList:item3"

Can I somehow accomplish this with android:dependency? Something like android:dependency="itemList:item3"

谢谢!

推荐答案

你可以做这样的事情的唯一方法是编程.

The only way you can do something like this is programmaticly.

您必须在 ListPreference 上设置一个更改侦听器,然后启用/禁用另一个.

You'd have to set up an change listener on the ListPreference and then enable/disable the other one.

itemList = (ListPreference)findPreference("itemList");
itemList2 = (ListPreference)findPreference("itemList2");
itemList.setOnPreferenceChangeListener(new
Preference.OnPreferenceChangeListener() {
  public boolean onPreferenceChange(Preference preference, Object newValue) {
    final String val = newValue.toString();
    int index = itemList.findIndexOfValue(val);
    if(index==3)
      itemList2.setEnabled(true);
    else
      itemList2.setEnabled(false);
    return true;
  }
});

如果我是你,如果第一个设置不正确,我什至不会显示第二个偏好.为此,您必须手动声明首选项(而不是在 XML 中)并添加/删除它,而不是启用/禁用.

If I were you I wouldn't even show the second preference if the first isn't set properly. To do that you have to declare the preference manually (not in the XML) and add/remove it instead of enabling/disabling.

这不是你见过的最好的答案吗?!

Now isn't this the bestest answer you've ever seen?!

伊曼纽尔

这篇关于ListPreference 依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:ListPreference 依赖项

基础教程推荐