我尝试编辑@waterdragon的解决方案,但被“peer rejected”了。不确定为什么,因为它仍然是他的解决方案,但提供了一个具体的例子。
子类化ListPreference
类,并覆盖setValue
和shouldDisableDependence
方法。
setValue
将在值实际更改时调用super.setValue
之后调用notifyDependencyChange(shouldDisableDependents())
。
shouldDisableDependence
仅在当前值为item3或存储在mDepedenceValue
中的任何其他所需值时返回false。
package xxx;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.ListPreference;
import android.util.AttributeSet;
import xxx.R;
public class DependentListPreference extends ListPreference {
private final String CLASS_NAME = this.getClass().getSimpleName();
private String dependentValue = "";
public DependentListPreference(Context context) {
this(context, null);
}
public DependentListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DependentListPreference);
dependentValue = a.getString(R.styleable.DependentListPreference_dependentValue);
a.recycle();
}
}
@Override
public void setValue(String value) {
String mOldValue = getValue();
super.setValue(value);
if (!value.equals(mOldValue)) {
notifyDependencyChange(shouldDisableDependents());
}
}
@Override
public boolean shouldDisableDependents() {
boolean shouldDisableDependents = super.shouldDisableDependents();
String value = getValue();
return shouldDisableDependents || value == null || !value.equals(dependentValue);
}
}
更新你的attrs.xml文件:
<attr name="dependentValue" format="string" />
<declare-styleable name="DependentListPreference">
<attr name="dependentValue" />
</declare-styleable>
在您的偏好设置 XML 中,将它与任何依赖于它的其他偏好设置相关联:
<xxx.DependentListPreference
android:key="pref_key_wifi_security_type"
android:title="Wi-Fi Security Type"
app:dependentValue="1"
android:entries="@array/wifi_security_items"
android:entryValues="@array/wifi_security_values" />
<EditTextPreference
android:key="pref_key_wifi_security_key"
android:title="WPA2 Security Key"
android:summary="Tap to set a security key"
android:password="true"
android:dependency="pref_key_wifi_security_type" />