android DatePicker跟TimePicke用法
android DatePicker和TimePicke用法
DatePicker和TimePicker都是从FrameLayout派生而来。
简单的例子实现对时间监听。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="选择时间" /> <DatePicker android:id="@+id/datepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <TimePicker android:id="@+id/timepicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <EditText android:id="@+id/et" android:layout_width="fill_parent" android:layout_height="wrap_content" android:editable="false" android:cursorVisible="false" /> </LinearLayout>
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+"分"); } }
运行效果如图: