Android NumberPicker with Formatter doesn't format on first rendering

前端 未结 9 1833

I have a NumberPicker that has a formatter that formats the displayed numbers either when the NumberPicker spins or when a value is entered manually. This works fine, but wh

9条回答
  •  爱一瞬间的悲伤
    2020-12-01 09:37

    The following solution worked out for me for APIs 18-26 without using reflection, and without using setDisplayedValues().

    It consists of two steps:

    1. Make sure the first element shows by setting it's visibility to invisible (I used Layout Inspector to see the difference with when it shows, it's not logical but View.INVISIBLE actually makes the view visible).

      private void initNumberPicker() {
       // Inflate or create your BugFixNumberPicker class
       // Do your initialization on bugFixNumberPicker...
      
       bugFixNumberPicker.setFormatter(new NumberPicker.Formatter() {
          @Override
          public String format(final int value) {
              // Format to your needs
              return aFormatMethod(value);
          }
       });
      
       // Fix for bug in Android Picker where the first element is not shown
       View firstItem = bugFixNumberPicker.getChildAt(0);
        if (firstItem != null) {
          firstItem.setVisibility(View.INVISIBLE);
        }
      }
      
    2. Subclass NumberPicker and make sure no click events go through so the glitch where picker elements disapear on touch can't happen.

      public class BugFixNumberPicker extends NumberPicker {
      
       public BugFixNumberPicker(Context context) {
          super(context);
       }
      
       public BugFixNumberPicker(Context context, AttributeSet attrs) {
          super(context, attrs);
       }
      
       public BugFixNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
          super(context, attrs, defStyleAttr);
       }
      
       @Override
       public boolean performClick() {
          return false;
       }
      
       @Override
       public boolean performLongClick() {
          return false;
       }
      
       @Override
       public boolean onInterceptTouchEvent(MotionEvent event) {
          return false;
       }
      }
      

提交回复
热议问题