Last active
April 30, 2018 17:51
-
-
Save afarber/609c4b2ce52a6ae41453 to your computer and use it in GitHub Desktop.
NumberPickerPreference for Android: saves number picker value as integer
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
import android.content.Context; | |
import android.content.res.TypedArray; | |
import android.preference.DialogPreference; | |
import android.util.AttributeSet; | |
import android.util.TypedValue; | |
import android.view.View; | |
import android.widget.NumberPicker; | |
import android.widget.TextView; | |
public class NumberPickerPreference extends DialogPreference { | |
private NumberPicker mPicker; | |
private int mNumber = 0; | |
public NumberPickerPreference(Context context, AttributeSet attrs) { | |
this(context, attrs, 0); | |
} | |
public NumberPickerPreference(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
setPositiveButtonText(android.R.string.ok); | |
setNegativeButtonText(android.R.string.cancel); | |
} | |
@Override | |
protected View onCreateDialogView() { | |
mPicker = new NumberPicker(getContext()); | |
mPicker.setMinValue(1); | |
mPicker.setMaxValue(100); | |
mPicker.setValue(mNumber); | |
return mPicker; | |
} | |
@Override | |
protected void onDialogClosed(boolean positiveResult) { | |
if (positiveResult) { | |
mPicker.clearFocus(); | |
setValue(mPicker.getValue()); | |
} | |
} | |
@Override | |
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { | |
setValue(restoreValue ? getPersistedInt(mNumber) : (Integer) defaultValue); | |
} | |
public void setValue(int value) { | |
if (shouldPersist()) { | |
persistInt(value); | |
} | |
if (value != mNumber) { | |
mNumber = value; | |
notifyChanged(); | |
} | |
} | |
@Override | |
protected Object onGetDefaultValue(TypedArray a, int index) { | |
return a.getInt(index, 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Complete usage example: https://github.com/afarber/android-newbie/tree/master/MyPrefs
Screenshot: https://github.com/afarber/android-newbie/blob/master/MyPrefs/screenshot.png