Skip to content

Instantly share code, notes, and snippets.

@trinhduyhung
Forked from Sloy/AutoSummaryListPreference
Created October 1, 2016 11:07
Show Gist options
  • Save trinhduyhung/ba6ab2ec7c2dfb4d91ce0c9b9f5621eb to your computer and use it in GitHub Desktop.
Save trinhduyhung/ba6ab2ec7c2dfb4d91ce0c9b9f5621eb to your computer and use it in GitHub Desktop.
Android custom ListPreference which shows its selected value as summary, as suggested in the official guidelines. No need to use OnPreferenceChangeListener in the Activity or anything like that. Only assign entries and entryValues.
package com.your.package;
import android.content.Context;
import android.preference.ListPreference;
import android.util.AttributeSet;
/**
* Created by Rafa Vázquez on 29/06/13.
*
* ListPreference item that shows its selected value as summary.
* Use in the XML just like the normal ListPreference.
*
* License:
* -------------------------------------------------
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
public class AutoSummaryListPreference extends ListPreference {
public AutoSummaryListPreference(Context context) {
this(context, null);
}
public AutoSummaryListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
setSummary(getSummary());
}
}
@Override
public CharSequence getSummary() {
int pos = findIndexOfValue(getValue());
return getEntries()[pos];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment