Change CheckBoxPreference summary based on checked state
Asked Answered
E

2

6

I am trying to create an App where the preference summary changes based on the checked state of a CheckBoxPreference.

I am not quite sure how to query preferences since a good old isChecked() won't work.

Excel answered 31/7, 2012 at 11:37 Comment(1)
How isChecked() doesn't work? Post your code.Discourse
C
17

Would be much simpler if you just used android:summaryOff and android:summaryOn in your preference layout. No code required. E.g:

<CheckBoxPreference
        android:enabled="true"
        android:key="alerts"
        android:title="Alerts" 

        android:summaryOn="You will get notified when something interesting happens"
        android:summaryOff="You will not be notified"
        /> 

See: http://developer.android.com/reference/android/preference/CheckBoxPreference.html

Cloverleaf answered 25/9, 2013 at 7:11 Comment(0)
D
2
public class Preferences extends PreferenceActivity
        implements OnSharedPreferenceChangeListener {

    public final static String KEY_CHECK = "check";
    private CheckBoxPreference mCheckBoxPreference;

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        addPreferencesFromResource(R.xml.preferences);
        mCheckBoxPreference = (CheckBoxPreference) getPreferenceScreen()
            .findPreference(KEY_CHECK);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        if (key.equals(KEY_CHECK)) {
            if (mCheckPreference.isChecked()) {
                mCheckPreference.setSummary(mCheckPreference.getEntry());
            }
        }
    }
}
Discourse answered 31/7, 2012 at 12:57 Comment(2)
Your code is giving me errors saying that onSharedPreferenceChangeListner is an unknown entity. Why is that?Excel
Have you imported import android.content.SharedPreferences.OnSharedPreferenceChangeListener; ? or try to use SharedPreferences.OnSharedPreferenceChangeListener instead.Discourse

© 2022 - 2024 — McMap. All rights reserved.