I\'m creating lists in a shared preference and when the onPreferenceChanged() method is called I want to extract the index of the item in the list or an integer value in som
Here's a ListIntegerPreference class I use (written for com.android.support:preference-v7:24.0.0). It overwrites a few methods and converts between Integer and String where possible, so that the base ListPreference does not recognise, that you are working with Integers instead of Strings.
public class ListIntegerPreference extends ListPreference
{
public ListIntegerPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
{
super(context, attrs, defStyleAttr, defStyleRes);
}
public ListIntegerPreference(Context context, AttributeSet attrs, int defStyleAttr)
{
super(context, attrs, defStyleAttr);
}
public ListIntegerPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ListIntegerPreference(Context context)
{
super(context);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue)
{
int defValue = defaultValue != null ? Integer.parseInt((String)defaultValue) : 0;
int value = getValue() == null ? 0 : Integer.parseInt(getValue());
this.setValue(String.valueOf(restoreValue ? this.getPersistedInt(value) : defValue));
}
@Override
public void setValue(String value)
{
try
{
Field mValueField = ListPreference.class.getDeclaredField("mValue");
mValueField.setAccessible(true);
Field mValueSetField = ListPreference.class.getDeclaredField("mValueSet");
mValueSetField.setAccessible(true);
String mValue = (String)mValueField.get(this);
boolean mValueSet = (boolean)mValueSetField.get(this);
boolean changed = !TextUtils.equals(mValue, value);
if(changed || !mValueSet)
{
mValueField.set(this, value);
mValueSetField.set(this, mValueSet);
this.persistInt(Integer.parseInt(value));
if(changed) {
this.notifyChanged();
}
}
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
I'm using this with creating ListPreferences values via code, just try it. It may work right away, or maybe you need to override additional functions. If so, this is a good start and shows you how you can do it...