android numberpicker for floating point numbers

前端 未结 3 1231
情书的邮戳
情书的邮戳 2021-02-06 05:22

The user of our app should be able to adjust a floating point number. At the moment, I filled an ArrayAdapter with all possible values and attached it to a spinner.

This

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-06 05:39

    Another solution is to combine two numberfields into one component. See the Money Picker Example. Its advantage is that you don't have to initialize all possible double values for your spinner.

    You may also need to attach special digits formatting, like "00", "0123" or other, using java.lang.String.format() function. Example is here.

    1. Add Double Picker xml-layout:

      
      
        
      
        
      
        
      
        
      
      
      
    2. Add custom Double Picker class:

      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. Use new Double Picker component in your activity xml:

      
      

提交回复
热议问题