1. 程式人生 > >設定DatePickerDialog主題顏色及起始日期

設定DatePickerDialog主題顏色及起始日期

一、設定DatePickerDialog主題顏色

如圖:
這裡寫圖片描述

程式碼:

findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //通過values和values-v21下的MyDatePickerDialogTheme改變顏色,
                new DatePickerDialog(MainActivity.this
, R.style.MyDatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { mYear = year; mMonth = month; mDay = dayOfMonth; mDateTv.setText(mYear + "-"
+ (mMonth + 1) + "-" + mDay); } }, mYear, mMonth, mDay).show(); } });

改變DatePickerDialog主題顏色步驟:

1、在values/style.xml新增:

 <style name="MyDatePickerDialogTheme" parent="@android:style/Theme.Holo.Light.Dialog"
> <item name="android:windowIsTranslucent">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowContentOverlay">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> <item name="android:backgroundDimEnabled">true</item> <item name="android:textColor">@color/red</item> </style>

2、在res下新建目錄values-v21,新建style.xml檔案,內容:

<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
        <item name="android:colorPrimary">@color/red</item>
        <item name="android:colorPrimaryDark">@color/red</item>
        <item name="android:colorAccent">@color/red</item>
    </style>

二、設定DatePickerDialog的起始日期和結束日期

public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,
                        R.style.MyDatePickerDialogTheme,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                mYear = year;
                                mMonth = month;
                                mDay = dayOfMonth;
                                mEdt.setText(mYear + "-" + (mMonth + 1) + "-" + mDay);
                            }
                        },
                        mYear, mMonth, mDay);
                //設定起始日期和結束日期
                DatePicker datePicker = datePickerDialog.getDatePicker();
                //datePicker.setMinDate();
                datePicker.setMaxDate(System.currentTimeMillis());
                datePickerDialog.show();
            }

這裡寫圖片描述