android日期選擇控件DatePickerDialog

samz5642 8年前發布 | 44K 次閱讀 Android開發 移動開發

來自: http://www.jcodecraeer.com//a/anzhuokaifa/androidkaifa/2014/0816/1653.html


使用DatePickerDialog:

final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
new DatePickerDialog(DialogSample.this,
                mDateSetListener,
                mYear, mMonth, mDay).show();

上面的代碼展示了如何顯示一個日期選擇控件(注意僅僅是顯示)。更詳細的使用方法這里就不討論了,這篇文章主要是研究它的外觀。
自從ics之后DatePickerDialog在不同的主題下有不同的外觀,如果你的主題不是holo風格,那么DatePickerDialog的樣式如下:

而如果你的主題是holo風格,在代碼相同的情況下又是這樣:

不管從外觀還是交互上,holo風格下的DatePickerDialog都要好很多,其實這完全就是兩個迥異的dialog。

為什么在不同的主題下會完全不同呢?holo最多在顏色上更扁平化而已,一般不會影響到控件的功能,但是兩個dialog中一個是通過點擊來改變日期,一個是通過滑動來改變日期。那么造成這個結果的原因是什么呢?

一開始猜想是在DatePickerDialog的初始化中判斷了主題,然后調用了不同的DatePicker,仔細研究了DatePickerDialog的源碼,發現自己錯了,其實關鍵因素是選擇日期的NumberPicker控件,這個控件在holo下所用的布局跟非holo不同。

NumberPicker的代碼注釋中是這樣說的:

* If the current theme is derived from {@link android.R.style#Theme} the widget
* presents the current value as an editable input field with an increment button
* above and a decrement button below.


* If the current theme is derived from {@link android.R.style#Theme_Holo} or
* {@link android.R.style#Theme_Holo_Light} the widget presents the current
* value as an editable input field with a lesser value above and a greater
* value below. Tapping on the lesser or greater value selects it by animating
* the number axis up or down to make the chosen value current. Flinging up
* or down allows for multiple increments or decrements of the current value.
* Long pressing on the lesser and greater values also allows for a quick change
* of the current value. Tapping on the current value allows to type in a
* desired value.

為了在2.3中使用holo風格的DatePickerDialog,只能將ics中holo風格下的DatePickerDialog獨立出來,當作一個第三方控件來使用,而不使用android.app.DatePickerDialog。

github上已經有開源項目將這個DatePickerDialog分離了出來。

github地址:https://github.com/SimonVT/android-datepicker

需要注意的是這個DatePickerDialog項目并沒有將自身需要用到的numberpicker和calendarview兩個控件集成上去,因此你在引用項目的時候需要自己下載作者提供的源碼地址,然后手動添加依賴關系。



 本文由用戶 samz5642 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!