您必須將最後選擇的位置NumberPicker
保存到SharedPreferences
。在那之後,每次你打開NumberPicker
,你應該使用設置默認選擇的位置爲它void setValue (int value)
final String[] power = { "0.00", "0.25", "0.50", "0.75s", "1.00s" };
NumberPicker numberPicker = (NumberPicker) findViewById(R.id.numberPicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(power.length - 1);
numberPicker.setDisplayedValues(power);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// any time your number picker change, we will save it to SharedPreferences
saveIntToSharedPreferences(mContext, PREF_NUMBER_PICKER_LAST_SELECTED_POSITION, newVal);
}
});
// when we open screen, we will select the last selected value by use setValue(...)
numberPicker.setValue(
getIntFromSharedPreferences(mContext, PREF_NUMBER_PICKER_LAST_SELECTED_POSITION));
輔助功能保存/從中獲取整數SharedPreferences
private void saveIntToSharedPreferences(Context context, String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
private int getIntFromSharedPreferences(Context context, String key) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getInt(key, 0);
}