这里有新鲜出炉的精品教程,程序狗速度看过来!
Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。
本篇文章主要介绍了Android之日期时间选择控件DatePicker和TimePicker实例,具有一定的参考价值,有兴趣的可以了解一下
这个月根据需求在项目中做了一个时间选择器,虽然没有用到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) findViewById(R.id.ll_time);
- tvTime = (TextView) findViewById(R.id.tv_time);
- llDate.setOnClickListener(this);
- llTime.setOnClickListener(this);
- }
2.2 创建相关变量
使用Calendar类获取当前的日期时间。
- private int year, month, day, hour, minute;
- private void initDateTime() {
- Calendar calendar = Calendar.getInstance();
- year = calendar.get(Calendar.YEAR);
- month = calendar.get(Calendar.MONTH) + 1;
- day = calendar.get(Calendar.DAY_OF_MONTH);
- hour = calendar.get(Calendar.HOUR);
- minute = calendar.get(Calendar.MINUTE);
- }
注意,
获取到的月份下标是从0开始的,值为0时表示一月份,1时表示二月份,以此类推,所以必须加上1。
- calendar.get(Calendar.MONTH)
创建两个StringBuffer变量,用于拼接获取到的时间数据。
- private StringBuffer date, time;
3、日期选择控件DatePicker
这里我们选择自定义AlertDialog的形式来显示选择控件。
日期选择控件自定义布局dialog_date.xml如下:
- <?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="wrap_content"
- android:gravity="center_horizontal"
- android:orientation="vertical">
- <DatePicker
- android:id="@+id/datePicker"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:calendarViewShown="false"
- android:endYear="2027"
- android:startYear="2007" />
- </LinearLayout>
只需放置一个DatePicker控件即可。不同版本的Android的DatePicker控件外观可能有所不同,比如Android4.4上是滚轮的形式,在7.0上则是一个日历视图。为了避免在4.4等低版本上显示出日历视图占用太多空间,可以将
属性设为fasle。
- android:calendarViewShown
继承接口
,实现日期改变的监听方法:
- DatePicker.OnDateChangedListener
- @Override
- public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
- this.year = year;
- this.month = monthOfYear;
- this.day = dayOfMonth;
- }
这样就可以获取到用户选择的年月日数值了。下面就是创建AlertDialog了:
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- if (date.length() > 0) { //清除上次记录的日期
- date.delete(0, date.length());
- }
- tvDate.setText(date.append(String.valueOf(year)).append("年").append(String.valueOf(month)).append("月").append(day).append("日"));
- dialog.dismiss();
- }
- });
- builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- final AlertDialog dialog = builder.create();
- View dialogView = View.inflate(context, R.layout.dialog_date, null);
- final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);
- dialog.setTitle("设置日期");
- dialog.setView(dialogView);
- dialog.show();
- //初始化日期监听事件
- datePicker.init(year, month - 1, day, this);
DatePicker需要调用init方法初始化,传入年月日数值和OnDateChangedListener对象。要记住我们前面在给month赋值时已经是对应的月份数值了,而这里需要的是下标值,所以要减1。
运行之后,效果如图所示:
4、时间选择控件TimePicker
这里我们同样需要一个自定义的AlertDialog布局:
- <?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="wrap_content"
- android:gravity="center"
- android:orientation="vertical">
- <TimePicker
- android:id="@+id/timePicker"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"></TimePicker>
- </LinearLayout>
同样,我们需要监听时和分的变化,所以继承TimePicker.OnTimeChangedListener接口,实现以下的方法:
- @Override
- public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
- this.hour = hourOfDay;
- this.minute = minute;
- }
时间选择控件的初始化跟日期选择控件的有所不同,DatePicker一个init方法解决,但TimePicker的工作量稍大一点。看下面代码:
- timePicker.setCurrentHour(hour);
- timePicker.setCurrentMinute(minute);
- timePicker.setIs24HourView(true); //设置24小时制
- timePicker.setOnTimeChangedListener(this);
除了要设置当前要显示的时和分之外,还要设置是24小时制还是12小时制。
效果图如下:
5、完整的MainActivity代码
- package com.lindroid.datetimepickerdemo;
- import android.app.AlertDialog;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.view.View;
- import android.widget.DatePicker;
- import android.widget.LinearLayout;
- import android.widget.TextView;
- import android.widget.TimePicker;
- import java.util.Calendar;
- public class MainActivity extends AppCompatActivity implements View.OnClickListener,
- DatePicker.OnDateChangedListener,
- TimePicker.OnTimeChangedListener {
- private Context context;
- private LinearLayout llDate,
- llTime;
- private TextView tvDate,
- tvTime;
- private int year,
- month,
- day,
- hour,
- minute;
- //在TextView上显示的字符
- private StringBuffer date,
- time;
- @Override protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- context = this;
- date = new StringBuffer();
- time = new StringBuffer();
- initView();
- initDateTime();
- }
- /**
- * 初始化控件
- */
- private void initView() {
- llDate = (LinearLayout) findViewById(R.id.ll_date);
- tvDate = (TextView) findViewById(R.id.tv_date);
- llTime = (LinearLayout) findViewById(R.id.ll_time);
- tvTime = (TextView) findViewById(R.id.tv_time);
- llDate.setOnClickListener(this);
- llTime.setOnClickListener(this);
- }
- /**
- * 获取当前的日期和时间
- */
- private void initDateTime() {
- Calendar calendar = Calendar.getInstance();
- year = calendar.get(Calendar.YEAR);
- month = calendar.get(Calendar.MONTH) + 1;
- day = calendar.get(Calendar.DAY_OF_MONTH);
- hour = calendar.get(Calendar.HOUR);
- minute = calendar.get(Calendar.MINUTE);
- }
- @Override public void onClick(View v) {
- switch (v.getId()) {
- case R.id.ll_date:
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {
- if (date.length() > 0) { //清除上次记录的日期
- date.delete(0, date.length());
- }
- tvDate.setText(date.append(String.valueOf(year)).append("年").append(String.valueOf(month)).append("月").append(day).append("日"));
- dialog.dismiss();
- }
- });
- builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- final AlertDialog dialog = builder.create();
- View dialogView = View.inflate(context, R.layout.dialog_date, null);
- final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.datePicker);
- dialog.setTitle("设置日期");
- dialog.setView(dialogView);
- dialog.show();
- //初始化日期监听事件
- datePicker.init(year, month - 1, day, this);
- break;
- case R.id.ll_time:
- AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
- builder2.setPositiveButton("设置", new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {
- if (time.length() > 0) { //清除上次记录的日期
- time.delete(0, time.length());
- }
- tvTime.setText(time.append(String.valueOf(hour)).append("时").append(String.valueOf(minute)).append("分"));
- dialog.dismiss();
- }
- });
- builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Override public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- AlertDialog dialog2 = builder2.create();
- View dialogView2 = View.inflate(context, R.layout.dialog_time, null);
- TimePicker timePicker = (TimePicker) dialogView2.findViewById(R.id.timePicker);
- timePicker.setCurrentHour(hour);
- timePicker.setCurrentMinute(minute);
- timePicker.setIs24HourView(true); //设置24小时制
- timePicker.setOnTimeChangedListener(this);
- dialog2.setTitle("设置时间");
- dialog2.setView(dialogView2);
- dialog2.show();
- break;
- }
- }
- /**
- * 日期改变的监听事件
- *
- * @param view
- * @param year
- * @param monthOfYear
- * @param dayOfMonth
- */
- @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
- this.year = year;
- this.month = monthOfYear;
- this.day = dayOfMonth;
- }
- /**
- * 时间改变的监听事件
- *
- * @param view
- * @param hourOfDay
- * @param minute
- */
- @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
- this.hour = hourOfDay;
- this.minute = minute;
- }
- }
来源: http://www.phperz.com/article/17/0827/337619.html