Android 时间日期选择器的用法

时间:2022-06-13 18:09:58
<?xml version="1.0" encoding="utf-8"?>
package com.example.data;

import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class DataActivity extends Activity {

	private int year;
	private int month;
	private int day;
	private int hour;
	private int minute;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_data);
		DatePicker datePicker =(DatePicker) findViewById(R.id.datepicker);
		TimePicker timePicker = (TimePicker) findViewById(R.id.timepicker);
		
		Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
		hour = c.get(Calendar.HOUR);
		minute = c.get(Calendar.MINUTE);
		
		datePicker.init(year, month, day, new OnDateChangedListener()
		{
			@Override
			public void onDateChanged(DatePicker arg0, int year, int month, int day)
			{
				DataActivity.this.year = year;
				DataActivity.this.month = month;
				DataActivity.this.day = day;
				
				showDate(year, month, day, hour, minute);
			}
		});
		
		timePicker.setOnTimeChangedListener(new OnTimeChangedListener()
		{
			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute)
			{
				DataActivity.this.hour = hourOfDay;
				DataActivity.this.minute = minute;
				
				showDate(year, month, day, hour, minute);
			}
		});
		
	}

	protected void showDate(int year, int month, int day, int hour,
			int minut2) {
		// TODO Auto-generated method stub
		EditText show = (EditText) findViewById(R.id.show);
		show.setText("您选择的日期为:" + year + "年" + (month + 1) + "月" + day + "日" + hour + "时" + minute + "分");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.data, menu);
		return true;
	}

}
效果图:
Android 时间日期选择器的用法