android DatePicker和TimePicke用法

DatePicker和TimePicker都是从FrameLayout派生而来。

简单的例子实现对时间监听。




    
    
    
    

 

package com.ly;

import java.util.Calendar;

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

/**
 * @author kurting
 * 两个时间控件监听
 *
 */
public class TimeExampleActivity extends Activity {
	private int year;
	private int month;
	private int day;
	private int hour;
	private int minute;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DatePicker datapicker = (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);
        datapicker.init(year, month, day, new OnDateChangedListener() {
			
			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
		TimeExampleActivity.this.year=year;
		TimeExampleActivity.this.month=monthOfYear;
		TimeExampleActivity.this.day=dayOfMonth;
		showDate(year,month,day,hour,minute);
			}
		});
        timepicker.setOnTimeChangedListener(new OnTimeChangedListener() {
			
			@Override
			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
				// TODO Auto-generated method stub
				TimeExampleActivity.this.hour=hourOfDay;
				TimeExampleActivity.this.minute=minute;
			}
		});
    }
 	private void showDate(int year, int month, int day, int hour,int minute) {
		EditText et = (EditText) findViewById(R.id.et);
		et.setText(year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分");
	}
}
 

 

 

运行效果如图:


android DatePicker和TimePicke用法_第1张图片

你可能感兴趣的:(android)