Created
June 29, 2013 13:16
-
-
Save Sloy/5891065 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | |
} | |
} |
Just in case the index is out of bound. I had to try this:
@Override
public CharSequence getSummary() {
int pos = findIndexOfValue(getValue());
try{
return getEntries()[pos];
}catch (Exception e){
e.printStackTrace();
}
return super.getSummary();
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's amazing! Great work! It is the most elegant solution which I found in Internet, very simple for implementation. Especially for beginners like me. Thank you.