Android DatePickerDialog 只顯示年月

Android DatePickerDialog 只顯示年月

今天寫一個日期控件,默認顯示年月日,但是我現在只想顯示年月,在網上找了一個比較簡單容易了理解的方法,分享如下:

先看一個效果圖:
處理前:  處理後:

實現的代碼:

    1. 通過遍歷方法查找DatePicker裏的子控件:年、月、日
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;
    } 

  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)((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
        } 

如果想隱藏年,把getChildAt(2)改爲getChildAt(0)...

  3.補充:如果標題欄也想改,需要自定義並實現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(year + "年" + (month + 1) + "月");
        }
    }



發佈了13 篇原創文章 · 獲贊 31 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章