ListPreference dependency

By : shuwo
Source: Stackoverflow.com
Question!

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" />

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

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

Thanks!

By : shuwo


Answers

I tried to edit @waterdragon solution but it was "peer rejected". Not sure why because it is still his solution but provides a concrete example.

Subclass ListPreference class, and override setValue and shouldDisableDependence methods.

setValue will call notifyDependencyChange(shouldDisableDependents()) after super.setValue when the value is actually changed.

shouldDisableDependence returns false only if the current value is item3, or any other desired value stored in 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);
    }
}

Update your attrs.xml:

By : ShellDude


This video can help you solving your question :)
By: admin