发表于: 2018-10-17 22:55:34

0 651


一、今天完成的事情

       学习了NumberPicker控件的基本用法,实现了一个选择日期的小功能

       首先在XML中添加控件,和别的控件没什么不同

<NumberPicker
   android:id="@+id/np_year"
   android:layout_width="0dp"
   android:layout_height="0dp"
   app:layout_constraintTop_toBottomOf="@+id/view_top"
   app:layout_constraintBottom_toTopOf="@+id/tv_year"
   app:layout_constraintStart_toStartOf="parent"
   app:layout_constraintEnd_toStartOf="@+id/np_month">
</NumberPicker>

       然后Activity中(我这里是Fragment)初始化

//yearNP
yearNP = (NumberPicker) square.findViewById(R.id.np_year);
yearNP.setMaxValue(MyCalendar.getSysYearInt());
yearNP.setMinValue(1900);
yearNP.setValue(year);
yearNP.setFocusable(true);
yearNP.setFocusableInTouchMode(true);
yearNP.setOnValueChangedListener(yearChangeListener);

      setMaxValue是设置显示最大的数值,这里取了当前系统的年份

      setMinValue设置的是最小值,也就是说这个NumberPicker显示的数值区间在1900-当前年份之间。

      setFocusable设置焦点状态

     然后就是给NumPicker添加一个数值变化的监听事件,当显示年份的Picker当前值是闰年时,2月份的天数应该改为29天,非闰年是28天。

private NumberPicker.OnValueChangeListener yearChangeListener 

    = new NumberPicker.OnValueChangeListener() {

   @Override
   /*
   普通闰年:能被4整除但不能被100整除的年份为普通闰年。(如2004年就是闰年,1999年不是闰年);
   世纪闰年:能被400整除的为世纪闰年。(如2000年是闰年,1900年不是闰年);
   计算公式:(year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)
    */
   public void onValueChange(NumberPicker arg0, int arg1, int arg2) {
       year = yearNP.getValue();
       if (((year % 4 == 0) && (year % 100 != 0) && (monthNP.getValue() == 2))
            || ((year % 400 == 0) && (monthNP.getValue() == 2))) {
         dayNP.setMaxValue(29);
       } else {
         dayNP.setMaxValue(28);
       }
   }
};

     这里对月份Picker也设置监听,大月31天,小月30天

private NumberPicker.OnValueChangeListener monthChangeListener

   = new NumberPicker.OnValueChangeListener() {

   @Override
   public void onValueChange(NumberPicker arg0, int arg1, int arg2) {
       month = monthNP.getValue();
       switch(month) {
          case 1:
          case 3:
          case 5:
          case 7:
          case 8:
          case 10:
          case 12:
            dayNP.setMaxValue(31);
            break;
          case 4:
          case 6:
          case 9:
          case 11:
            dayNP.setMaxValue(30);
            break;
          case 2:
              int year = yearNP.getValue();
              if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
                dayNP.setMaxValue(29);
              } else {
                dayNP.setMaxValue(28);
              }
            break;
          default:
            break;
       }
   }
};


二、明天计划的事情

     1.将头像显示为圆形

     2.做一个地区选择的功能


三、遇到的问题

 

四、收获

    NumberPicker




返回列表 返回列表
评论

    分享到