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);
}
}
}
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);
Firstly you can set default value for your listUnits
listpreference to celcius
or Fahrenheit
,according this you can make enable-disable your second listpreference.
Now when changing your Preference by selecting anyone of them you can follow below procedure.
1) implement OnSharedPreferenceChangeListener
in your MyPreferenceFragment
class and override the method onSharedPreferenceChanged
2) Code like below in your method
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if (key.equals("listUnits")) {
final String value = sharedPreferences.getString(key, "");
Preference Pref_cec=findPreference("listpalette");
if (value.equals("celcius")) {
wallpaperPref_admin.setEnabled(true);
}else{
wallpaperPref_admin.setEnabled(false);
}
}
}
Hope it will Help. Let me know if anything missing in my post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With