Android之日期时间选择控件DatePicker和TimePicker

本文详细介绍了如何在Android项目中使用DatePicker和TimePicker控件,包括初始化控件、创建相关变量、自定义显示方式,以及如何监听和处理用户选择的日期和时间。通过实例代码展示了这两个控件的完整用法。
摘要由CSDN通过智能技术生成

这个月根据需求在项目中做了一个时间选择器,虽然没有用到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
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值