我有数字选择器,我用字符串数组填充它。
final String[] power = {"0.00", "0.25", "0.50", "0.75","1.00"};
npPowerSecond.setMinValue(0);
npPowerSecond.setMaxValue(power.length - 1);
npPowerSecond.setDisplayedValues(power);
我显示如上所示的值。当我打开数字选择器时,它将显示“0.00”作为选定值。现在我选择“0.50”。现在,当我打开数字选择器时,它应显示“0.50”作为选定值。
你能帮帮我吗?我怎样才能做到这一点?答案 0 :(得分:3)
npPowerSecond.setValue(2);
使用setvalue进行设置。
答案 1 :(得分:1)
您必须将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);
}
答案 2 :(得分:0)
npPowerSecond.setValue(selectedNumber);
选择值后,将值设置为该数字选择器。我认为它会对你有帮助。