这个月根据需求在项目中做了一个时间选择器,虽然没有用到Android原生的时间选择控件,但我羞愧地发现自己竟然从来没有用过这方面控件!趁现在有时间,赶紧查缺补漏,写一篇博客吧。
(注:为了便于区分,本文将选择年月日的控件称为日期选择控件,将选择时分的控件称为时间选择控件。)
1、创建项目
新建一个项目,MainActivity的布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context="com.lindroid.datetimepickerdemo.MainActivity">
<LinearLayout
android:id="@+id/ll_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择日期:"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ededed"
android:padding="8dp"
android:textSize="18sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择时间:"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ededed"
android:padding="8dp"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
界面效果如下:
点击条目之后就会弹出日期或者时间选择控件,点击确定按钮后,就会将选择的结果显示在浅灰色的方框中。
2、初始化控件和创建相关变量
2.1 初始化控件
初始化控件,并为两个LinearLayout设置监听事件:
private void initView() {
llDate = (LinearLayout) findViewById(R.id.ll_date);
tvDate = (TextView) findViewById(R.id.tv_date);
llTime = (LinearLayout