2025-02-15

前言
  需求要隻顯示月和日的日歷控件,又不想自定義控件,最簡單的辦法就是隱藏顯示年的這個框瞭,但DatePickerDialog並沒有直接提供方法來操作,這裡分享一個笨辦法:)
  
正文
  一、效果圖
    1.1 默認
  
    1.2 處理後
  
 
  二、實現代碼
    2.1  代碼片段1
/**
 * 從當前Dialog中查找DatePicker子控件
 * 
 * @param group
 * @return
 */
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;
 

      代碼說明:
通過斷點也看到Dialog的ContentView裡有DatePicker子控件,這裡通過遍歷的辦法來查找這個控件。
 
    2.2  使用代碼
final Calendar cal = Calendar.getInstance();
mDialog = new CustomerDatePickerDialog(getContext(), this,
    cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
    cal.get(Calendar.DAY_OF_MONTH));
mDialog.show();
 
DatePicker dp = findDatePicker((ViewGroup) mDialog.getWindow().getDecorView());
if (dp != null) {
    ((ViewGroup) dp.getChildAt(0)).getChildAt(0).setVisibility(View.GONE);
 

      代碼說明:
        通過源碼可以看得到DatePicker內置三個NumberPicker控件,依次表示年、月、日,隱藏掉第一個即可。
 
 
    三、補充
      後續使用中發現標題欄也要改,通過查看DatePickerDialog源碼,需要自定義並實現onDateChanged方法才可實現,如下代碼:
class CustomerDatePickerDialog extends DatePickerDialog {
 
    public CustomerDatePickerDialog(Context context,
            OnDateSetListener callBack, int year, int monthOfYear,
            int dayOfMonth) {
        super(context, callBack, year, monthOfYear, dayOfMonth);
    }
 
    @Override
    public void onDateChanged(DatePicker view, int year, int month, int day) {
        super.onDateChanged(view, year, month, day);
        mDialog.setTitle((month + 1) + "月" + day + "日");
    }
}


作者“農民伯伯”

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *