Я пытался отредактировать решение @waterdragon, но оно было «отклонено». Не уверен, почему, потому что это все еще его решение, но дает конкретный пример.
Подкласс ListPreference
class и переопределение setValue
и shouldDisableDependence
методов.
setValue
вызовет notifyDependencyChange(shouldDisableDependents())
после super.setValue
, когда значение действительно изменится.
shouldDisableDependence
возвращает false, только если текущее значение равно item3 или любое другое требуемое значение, сохраненное в mDepedenceValue
.
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" />