Android:将自定义值设置为NumberPicker
我创建了一个自定义数字选择器,并使用布局充气器添加到布局中。 我想给数字选择器2,5,10设置三个值。通过使用setMinValue(1),setMaxValue(3)它只设置1到3个默认值Android:将自定义值设置为NumberPicker,android,android-layout,android-activity,Android,Android Layout,Android Activity,我创建了一个自定义数字选择器,并使用布局充气器添加到布局中。 我想给数字选择器2,5,10设置三个值。通过使用setMinValue(1),setMaxValue(3)它只设置1到3个默认值 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams ((int) RelativeLayout.LayoutParams.WRAP_CONTENT, (int) RelativeL
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
((int) RelativeLayout.LayoutParams.WRAP_CONTENT, (int) RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
np.setLayoutParams(params);
np.setMinValue(1);
np.setMaxValue(3);
np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
np.setValue(2);
我想设置2,5,10,而不是将1设置为3。
谁能告诉我如何在数字选择器中设置自定义值
提前感谢:)试试这样的东西,希望能对你有所帮助
NumberPicker picker = new NumberPicker(this);
picker.setMinValue(1);
picker.setMaxValue(3);
picker.setDisplayedValues( new int[] { 2, 5, 10 } );
更新:
您可以使用下面的代码检索所选号码
String value = picker.getDisplayedValues()[picker.getValue()];
感谢Mustanser为我们指明了正确的方向。需要注意的是,setDisplayedValues采用字符串数组,因此函数式答案是:
NumberPicker picker = new NumberPicker(this);
picker.setMinValue(1);
picker.setMaxValue(3);
picker.setDisplayedValues( new String[] { "2", "5", "10" } );
此外,确保正确解释picker.getValue()的结果也很重要,因为基础int值仍然从1到3运行:
int pick;
switch (picker.getValue()) {
case 1:
pick = 2;
break;
case 2:
pick = 5;
break;
case 3:
pick = 10;
break;
default:
//...
}
这就是为什么要使用switch选项的完整解决方案,特别是当您有许多值时,您可以这样做:
String value=numberPicker.getDisplayedValues()[i]代码>内部setOnValueChangedListener