由于app功能需要个精确到秒的日期时间对话框,网上找了很多,只找到一个满足需求的例子,是个完全自定义的对话框,但是也存在点问题(对2月的28、29的问题未作处理),所以尝试在网上现有的资料上进行改写,实现精确到秒的日期时间对话框,并对闰年进行了处理。首先上个效果图,效果图上的android版本为4.4.4和6.0,显示均为正常。
下面讲讲实现的思路及步骤:
思路:NumberPicker是Android3.0之后引入的一个控件,NumberPicker 是用于选择一组预定义好数字的控件。比如时间hour的选择只有0—23有效,则可以通过setMinValue和setMaxValue设定,年、月、日、时、分、秒的数字正好可以用NumberPicker来实现。其次,AlertDialog可以自定义显示,可以加载自定义布局,这样我们把NumberPicker 装载到AlertDialog中,就可以实现我们所需要的精确到秒的日期时间对话框了。
下面即是步骤:
首先在layout里创建布局文件,我这里分两行显示(其实可以实现一行显示,需要自己对每个NumberPicker 的显示大小进行控制,我因为时间有限,未做研究)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:layout_marginBottom="10dp"
android:paddingLeft="3.0dip"
android:paddingStart="3.0dip"
android:paddingEnd="3dp"
android:paddingRight="3dp" >
<NumberPicker
android:id="@+id/np_datetime_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@null" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/year"
android:textSize="20.0sp" />
<NumberPicker
android:id="@+id/np_datetime_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@null" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/month"
android:textSize="20.0sp" />
<NumberPicker
android:id="@+id/np_datetime_day"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@null" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/day"