Search code examples
androidandroid-settings

Enable and disable option in PreferenceActivity


I am new to creating PreferenceActivity. My question is how to enable and disable option in preference screen by changing other preference?

My prefs.xml:

<ListPreference
    android:entries="@array/units"
    android:entryValues="@array/lunits"
    android:key="listUnits"
    android:summary="Units schosssing"
    android:title="Units" android:defaultValue="C"/>

 <ListPreference
    android:entries="@array/palette"
    android:entryValues="@array/lpalette"
    android:key="listpalette"
    android:summary="Palette schosssing"
    android:title="Palette" 
    android:defaultValue="1"/>

In the listUnits there are 2 options, Celsius and Fahrenheit, so if user selects Celsius the listpalette should get enabled, and if user selects Fahrenheit becomes disabled, how can I do this?

My settings activity:

public class SettingsActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();             
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.prefs);
        }
    }

}

Solution

  • This code may be useful to you. Can take as reference.

    First take instance of both of the ListPreference and apply this method.

    ListPreference mlistUnits, mlistPalette;
    mlistUnits= (ListPreference)findPreference("listUnits");
    mlistPalette= (ListPreference)findPreference("listpalette");
    
    mlistUnits.setEnable(false);
    mlistPalette.setEnabled(true);
    

    and use below listner

    OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {    
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        // newValue is the value you choose
        return false;
    }
    };
    

    apply listener to ListPreference

    mlistPalette.setOnPreferenceChangeListener(listener);