DatePickerDialog用法及只显示年月隐藏日

在代码中用法:

private void showDatePicker() {
		//获取当前日期
		Calendar calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
		
		//创建并显示DatePickerDialog
		DatePickerDialog dialog = new DatePickerDialog(this, Datelistener, year, month, day);
		dialog.show();
		
		//只显示年月,隐藏掉日
		DatePicker dp = findDatePicker((ViewGroup) dialog.getWindow().getDecorView());
		if (dp != null) {
			((ViewGroup)((ViewGroup)dp.getChildAt(0)).getChildAt(0))
									.getChildAt(2).setVisibility(View.GONE);
			//如果想隐藏掉年,将getChildAt(2)改为getChildAt(0)
		}
	}

findDatePicker方法

private DatePicker findDatePicker(ViewGroup group) {
   if (group != null) {
      for (int i = 0, j = group.getChildCount(); i < j; i++) {
         View child = group.getChildAt(i);
         if (child instanceof DatePicker) {
            return (DatePicker) child;
         } else if (child instanceof ViewGroup) {
            DatePicker result = findDatePicker((ViewGroup) child);
            if (result != null)
               return result;
         }
      }
   }
   return null;
}

DateListener , new DatePickerDialog()时传入

private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
{
   /**params:view:该事件关联的组件
    * params:myyear:当前选择的年
    * params:monthOfYear:当前选择的月
    * params:dayOfMonth:当前选择的日
    */
   @Override
   public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {

      //修改year、month、day的变量值,以便以后单击按钮时,DatePickerDialog上显示上一次修改后的值
      year=myyear;
      month=monthOfYear;
      day=dayOfMonth;
      //更新日期
      updateDate();

   }
   //当DatePickerDialog关闭时,更新日期显示
   private void updateDate()
   {
      //在TextView上显示日期
      tvDate.setText(year+"年"+(month+1)+"月");
   }
};

本文参考:http://blog.csdn.net/lzt623459815/article/details/8479991

猜你喜欢

转载自blog.csdn.net/solocoder/article/details/83656042