Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate and deactivate a preference

I need an example-tutorial how to activate and deactivate an element in preference activity.

For example in the picture below when the Wi-Fi check box is unselected I can not touch the Network notification check box and it turns gray, when the Wi-Fi check box is selected then I can touch the other check box.

Also how can I populate the Add Wi-Fi network tab when the whi-fi checkbox is enabled?

enter image description here

like image 595
mkounal Avatar asked Aug 09 '12 07:08

mkounal


2 Answers

We need to add in out preferences.xml file in the preference which is depending from another preference the android:dependency="" code.

For example :

        <CheckBoxPreference
            android:key="checkBox"
            android:summary="On/Off"
            android:title="Enable" />

        <ListPreference
            android:entries="@array/listOptions"
            android:entryValues="@array/listValues"
            android:key="listpref"
            android:summary="List preference example"
            android:title="List preference"
            android:dependency="checkBox" />
like image 106
mkounal Avatar answered Oct 21 '22 11:10

mkounal


Your preferences activity should implement OnSharedPreferenceChangeListener. Be sure to register and unregister the activity with the listener.

Then in both onResume() and onSharedPreferenceChanged methods evaluate the state of the controlling preference to determine if the dependant preference should be enabled or disabled.

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        final String key) {
    if (key.equals(PREFERENCE_KEY)) {
        // handle setting enabled or disabled depending on value of preference
        if (sharedPreferences.getBoolean(key, false)) {
            // prefField.setenabled(true);
        } else {
            // prefField.setenabled(false);
        }

    }
}

If you also use a PreferenceCategory then you may also look to enable or disable the category as a whole.

like image 36
Phil H Avatar answered Oct 21 '22 11:10

Phil H