天天看點

[Android]隻顯示月和日的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 + "日");

    }

繼續閱讀