public class Activity01 extends Activity
{
TextViewm_TextView;
//声明dataPicker
DatePickerm_DatePicker;
//声明TimePicker
TimePickerm_TimePicker;
Button m_dpButton;
Button m_tpButton;
//java中的Calendar类
Calendar c;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
c=Calendar.getInstance();
m_TextView= (TextView) findViewById(R.id.TextView01);
m_dpButton = (Button)findViewById(R.id.button1);
m_tpButton = (Button)findViewById(R.id.button2);
//获取DataPicker对象
m_DatePicker = (DatePicker) findViewById(R.id.DatePicker01);
//初始化当前时间并设置监听
m_DatePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
//当日期更改在这里设置
c.set(year, monthOfYear, dayOfMonth);
}
});
//
m_TimePicker = (TimePicker) findViewById(R.id.TimePicker01);
//
m_TimePicker.setIs24HourView(true);
//
m_TimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute)
{
//当时间更改在这里设置
c.set(year, month, day, hourOfDay, minute, second);
}
});
m_dpButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
new DatePickerDialog(Activity01.this,
new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
//设置日历
}
},c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
}
});
m_tpButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
new TimePickerDialog(Activity01.this,
new TimePickerDialog.OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay,int minute)
{
//设置时间
}
},c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
}
});
}
}
对应的layout文件<?xml version="1.0" encoding="utf-8"?>
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:id="@+id/TextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:id="@+id/Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
android:id="@+id/Button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>