【问题标题】:android numberpicker for floating point numbers用于浮点数的 android numberpicker
【发布时间】:2012-11-18 17:10:36
【问题描述】:

我们应用的用户应该能够调整浮点数。目前,我用所有可能的值填充了一个 ArrayAdapter 并将它附加到一个微调器。

这个解决方案并没有真正达到我们的期望,因为微调框下拉框太高了。有没有更好的办法?我在看 Numberpicker - 但这似乎只适用于整数值。

有什么想法吗?

谢谢!

【问题讨论】:

标签: android spinner numberpicker


【解决方案1】:

NumberPicker 不仅适用于整数。甚至您也可以使用 Floats String 等。

请参阅this 并阅读相关内容。

教程:

我很久以前就这样使用过NumberPicker,在这里发帖可能会有用处:

    NumberPicker np;
    String nums[]= {"Select Fraction","1/64","1/32","3/64","1/16","5/64","3/32","7/64","1/8","9/64","5/32","11/64","3/16","13/64","7/32","15/64","1/4","17/64","9/32","19/64","5/16","21/64","11/32","23/64","3/8","25/64","13/32","27/64","7/16","29/64"};

            np = (NumberPicker) findViewById(R.id.np);

            np.setMaxValue(nums.length-1);
            np.setMinValue(0);
            np.setWrapSelectorWheel(false);
            np.setDisplayedValues(nums);
            np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); 

您可以将ArrayList 设为任何数据类型并分配它。

【讨论】:

  • 您的解决方案很棒!谢谢,但我有一个问题:当我有String nums[] 时,如何以编程方式设置值?
  • 如果你打算走这条路,根据我的评论,使用 Formatter 会更好:stackoverflow.com/questions/18464571/…
【解决方案2】:

另一种解决方案是将两个数字字段组合成一个组件。请参阅Money Picker Example。它的优点是您不必为微调器初始化所有可能的双精度值。

您可能还需要使用java.lang.String.format() 函数附加特殊数字格式,如“00”“0123” 或其他.例如here

  1. 添加双选择器 xml 布局:

    <LinearLayout
      xmlns:android = "http://schemas.android.com/apk/res/android"
      android:layout_width = "fill_parent"
      android:layout_height = "wrap_content"
      android:gravity = "center">
    
      <NumberPicker
        android:id = "@+id/integer_picker"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"/>
    
      <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:padding = "5dp"
        android:text = "@string/local_separator"
        android:textSize = "20sp"/>
    
      <NumberPicker
        android:id = "@+id/fraction_picker"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"/>
    
      <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "center"
        android:padding = "5dp"
        android:text = "@string/measure_unit_sign"
        android:textSize = "20sp"/>
    
    </LinearLayout>
    
  2. 添加自定义 Double Picker 类:

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.widget.NumberPicker;
    
    /**
     * UI component for double (floating point) values. Can be used
     * for money and other measures.
     */
    public class DoublePicker
      extends NumberPicker {
    
      private int decimals;
      private NumberPicker integerPicker;
      private NumberPicker fractionPicker;
    
      public DoublePicker(
        Context context) {
    
        super(
          context);
    
          LayoutInflater
            .from(
              context)
            .inflate(
              R.layout.double_picker,
              this);
    
          integerPicker =
            (NumberPicker) findViewById(
              R.id.integer_picker);
    
          fractionPicker =
            (NumberPicker) findViewById(
              R.id.fraction_picker);
      }
    
      public int getDecimals() {
    
        return decimals;
      }
    
      /**
       * Sets the amount of digits after separator.
       *
       * @param decimals Anount of decimals.
       */
      public void setDecimals(final int decimals) {
    
        this.decimals = decimals;
    
        this.setFormatter(new DoublePicker.Formatter() {
    
          @Override
          public String format(int i) {
    
            return String.format(
              "%." + decimals + "f",
              i);
          }
        });
      }
    
      public void setValue(double value) {
    
        integerPicker.setValue((int) value);
    
        fractionPicker.setValue(
          Integer.valueOf(
            String
              .valueOf(value)
              .split(".")
              [1]));
      }
    }
    
  3. 在您的活动 xml 中使用新的 Double Picker 组件:

    <com.example.DoublePicker
      android:id ="@+id/double_picker"
      android:layout_width ="match_parent"
      android:layout_height ="wrap_content" />
    

【讨论】:

    【解决方案3】:

    Kotlin 中,您可以使用这个方便的 NumberPicker 扩展对话框,它将您的 Double 值缩放到合适的 Int 范围并将 Int 值转换回 Doubles在调用任何回调之前。所以它基本上隐藏了NumberPicker只支持Int的事实。感觉NumberPicker居然会支持Double,试试看!

    这是您需要复制和粘贴片段扩展

    fun Fragment.showNumberPickerDialog(
        title: String,
        value: Double,
        range: ClosedRange<Double>,
        stepSize: Double,
        formatToString: (Double) -> String,
        valueChooseAction: (Double) -> Unit
    ) {
        val numberPicker = NumberPicker(context).apply {
            setFormatter { formatToString(it.toDouble() * stepSize) }
            wrapSelectorWheel = false
    
            minValue = (range.start / stepSize).toInt()
            maxValue = (range.endInclusive / stepSize).toInt()
            this.value = (value.toDouble() / stepSize).toInt()
    
            // NOTE: workaround for a bug that rendered the selected value wrong until user scrolled, see also: https://stackoverflow.com/q/27343772/3451975
            (NumberPicker::class.java.getDeclaredField("mInputText").apply { isAccessible = true }.get(this) as EditText).filters = emptyArray()
        }
    
        MaterialAlertDialogBuilder(context)
            .setTitle(title)
            .setView(numberPicker)
            .setPositiveButton("OK") { _, _ -> valueChooseAction(numberPicker.value.toDouble() * stepSize) }
            .setNeutralButton("Cancel") { _, _ -> /* do nothing, closes dialog automatically */ }
            .show()
    }
    

    现在您可以像这样使用它(在Fragment 中):

    showNumberPickerDialog(
        title = "Your Weight",
        value = 75.0, // in kilograms
        range = 10.0 .. 300.0,
        stepSize = 0.1,
        formatToString = { "$it kg" },
        valueChooseAction = { saveNewWeight(it) }
    )
    

    【讨论】:

    • 效果很好,主题需要从 Theme.MaterialComponents.some_theme 派生,不能从 AppCompat 派生
    猜你喜欢
    • 2013-08-30
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2016-03-10
    • 2016-04-14
    • 1970-01-01
    • 2022-12-19
    • 2013-05-11
    相关资源
    最近更新 更多