Android NumberPicker: Set min, max, default from XML

前端 未结 2 1650
逝去的感伤
逝去的感伤 2020-12-08 06:33

Is there a way to set the minimum, maximum and default values of a NumberPicker from the XML Layout?

I\'m doing it from within the Activity code:

np          


        
2条回答
  •  伪装坚强ぢ
    2020-12-08 06:56

    I had the same problem, this is how I solved it (according to the comment of MKJParekh):

    1. I created my own NumberPicker-Class

      package com.exaple.project;
      
      import android.annotation.TargetApi;
      import android.content.Context;
      import android.os.Build;
      import android.util.AttributeSet;
      import android.widget.NumberPicker;
      
      @TargetApi(Build.VERSION_CODES.HONEYCOMB)//For backward-compability
      public class MyNumberPicker extends NumberPicker {
      
          public MyNumberPicker(Context context) {
              super(context);
          }
      
          public MyNumberPicker(Context context, AttributeSet attrs) {
              super(context, attrs);
              processAttributeSet(attrs);
          }
      
          public MyNumberPicker(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
              processAttributeSet(attrs);
          }
          private void processAttributeSet(AttributeSet attrs) {
              //This method reads the parameters given in the xml file and sets the properties according to it
              this.setMinValue(attrs.getAttributeIntValue(null, "min", 0));
              this.setMaxValue(attrs.getAttributeIntValue(null, "max", 0));
          }
      }
      
    2. Now you can use this NumberPicker in your xml layout file

      
      

    Thanks to MKJParekh for his useful comment

提交回复
热议问题