Skip to content

Instantly share code, notes, and snippets.

@StelianMorariu
Created September 10, 2013 09:31
Show Gist options
  • Save StelianMorariu/6507088 to your computer and use it in GitHub Desktop.
Save StelianMorariu/6507088 to your computer and use it in GitHub Desktop.
Example of extending EditTextPreference to create a preference that saves numbers (EditTextPreference saves strings even if you specify "android:inputType=number ")
/*
* NumericPreference.java
*
*Copyright © Ropardo™ 2013.
*/
package ro.ropardo.imobiledistribution.utils;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
import android.util.Log;
/**
* @author Stelian Morariu
*
*/
public class NumericPreference extends EditTextPreference {
public NumericPreference(Context context) {
super(context);
}
public NumericPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NumericPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected String getPersistedString(String defaultReturnValue) {
long aux = -1l;
if (defaultReturnValue != null && defaultReturnValue.length() > 0) {
try {
aux = Long.valueOf(defaultReturnValue);
} catch (Exception e) {
Log.e(NumericPreference.class.getSimpleName(), "Invalid default value for Long : " + e.toString());
}
}
return String.valueOf(getPersistedLong(aux));
}
@Override
protected boolean persistString(String value) {
return persistLong(Long.valueOf(value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment