DatePicker和TimePicker是Android里面的高级控件,用户可以直接使用,用法跟普通的控件一样。
下面是一个实例程序:
MainActivity.java中的代码:
package com.example.androidnetworkprogram;
import java.util.Calendar;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
public class MainActivity extends Activity {
private DatePicker myDatePicker = null;
private TimePicker myTimePicker = null;
private Calendar myCalendar = null;
private int mYear,mMonth,mDay,mHour,mMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDatePicker = (DatePicker)this.findViewById(R.id.mydatapicker);
myTimePicker = (TimePicker)this.findViewById(R.id.mytimepicker);
myCalendar = Calendar.getInstance(); //获得系统日期和时间的Calendar实例
mYear = myCalendar.get(Calendar.YEAR);
mMonth = myCalendar.get(Calendar.MONTH);
mDay = myCalendar.get(Calendar.DAY_OF_MONTH);
mHour = myCalendar.get(Calendar.HOUR_OF_DAY);
mMinute = myCalendar.get(Calendar.MINUTE);
myDatePicker.init(mYear, mMonth, mDay, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
}
});
myTimePicker.setIs24HourView(true);
myTimePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
}
});
}
}
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<DatePicker
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mydatapicker"
android:layout_gravity="center"/>
<TimePicker
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mytimepicker"
android:layout_gravity="center"
/>
</LinearLayout>