2017-04-05 68 views
1

我有数字选择器,我用字符串数组填充它。当数字选择器第二次打开时突出显示选中的项目

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”作为选定的值。

你能帮我吗?我怎样才能做到这一点?

回答

3
npPowerSecond.setValue(2); 

使用setvalue进行设置。

0
npPowerSecond.setValue(selectedNumber); 

选择值后,将值设置为该号码选取器。我认为它会帮助你。

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); 
} 
相关问题