DatePickerDialog对话框和TimePickerDialog对话框比单独的DatePicker组件和TimePicker组件更好用,用法也比较简单,下面通过一个简单实例来演示它们的使用:
Activity:
package com.lovo;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获得设置日期按钮
Button dateBtn = (Button) findViewById(R.id.btn1);
// 获得设置时间按钮
Button timeBtn = (Button) findViewById(R.id.btn2);
// 为设置日期按钮绑定监听器
dateBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Calendar c = Calendar.getInstance();
// 直接创建一个DatePickerDialog对话框实例,并将它显示出来
new DatePickerDialog(MainActivity.this,
// 绑定监听器
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
TextView show = (TextView) findViewById(R.id.txt1);
show.setText("您选择了:" + year + "年" + monthOfYear
+ "月" + dayOfMonth + "日");
}
}
// 设置初始日期
, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c
.get(Calendar.DAY_OF_MONTH)).show();
}
});
// 为设置时间按钮绑定监听器
timeBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
// 创建一个TimePickerDialog实例,并把它显示出来
new TimePickerDialog(MainActivity.this,
// 绑定监听器
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view,
int hourOfDay, int minute) {
TextView show = (TextView) findViewById(R.id.txt2);
show.setText("您选择了:" + hourOfDay + "时" + minute
+ "分");
}
}
// 设置初始时间
, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE),
// true表示采用24小时制
true).show();
}
});
}
}
布局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="match_parent"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置日期" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置时间" />
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
附上图片效果:
点击按钮弹出下面对话框,可以选择日期或时间:
设置后的效果: