【问题标题】:Android: set custom value to the NumberPickerAndroid:为 NumberPicker 设置自定义值
【发布时间】:2015-10-16 04:54:22
【问题描述】:

我创建了一个自定义数字选择器并使用布局充气器添加到布局中。 我想为数字选择器 2、5、10 设置三个值。通过使用 setMinValue(1),setMaxValue(3) 它只设置 1 到 3 个默认数字。

 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。 谁能告诉我如何在数字选择器中设置自定义值

提前致谢:)

【问题讨论】:

    标签: android android-layout android-activity


    【解决方案1】:

    感谢 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]; inside setOnValueChangedListener
    【解决方案2】:

    尝试这样的事情希望它会帮助你

    NumberPicker picker = new NumberPicker(this);
    picker.setMinValue(1);
    picker.setMaxValue(3);
    picker.setDisplayedValues( new int[] { 2, 5, 10 } );
    

    更新:

    您可以使用下面的代码检索所选号码

    String value = picker.getDisplayedValues()[picker.getValue()];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2016-12-26
      • 2019-10-26
      • 2014-11-05
      相关资源
      最近更新 更多