Activity.java中:
private static final int DATE_PICKER_ID=1; //声明一个常量
result=(TextView)this.findViewById(R.id.result);
btnDate=(Button)this.findViewById(R.id.btnDate);
btnDate.setOnClickListener(new OnClickListener(){ //设置监听器
@Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID); //会调用onCreateDialog(int id)方法
}
});
布局文件:
<Button
android:id="@+id/btnDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/btnDate"/>
<TextView
android:id="@+id/result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
1、声明一个监听器,使用匿名内部类
DatePickerDialog.OnDateSetListener onDateSetListener=new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
result.setText(year+"-"+monthOfYear+"-"+dayOfMonth); //获得选择的日期(注意月份是从0开始的)
}
};
2、重写onCreateDialog(int id)方法
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id)
{
case DATE_PICKER_ID:
return new DatePickerDialog(this,onDateSetListener,2012,3,30); //显示的默认时间
}
return null;
}
本文详细介绍了在Android应用中如何实现日期选择器的功能,包括声明常量、设置监听器、重写onCreateDialog方法以及展示选择的日期。通过使用布局文件和Activity代码的结合,展示了如何在界面上呈现日期选择并获取用户选择的日期。
1516

被折叠的 条评论
为什么被折叠?



