DatePicker 日期选择控件 DatePickerDialog 日期选择对话框
1.main.xml
< ?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:id="@+id/dateDisplay" android:layout_width="fill_parent" android:textsize="20sp" android:layout_height="wrap_content">
</textview>
<button android:text="改变日期" android:id="@+id/pickDate" android:textsize="20sp" android:layout_width="wrap_content" android:layout_height="wrap_content">
</button>
</linearlayout>
其中文本框用来显示时间,按钮为了触发日期选择对话框,当然用其他组件来触发日期选择对话框也是的。
2.java代码
package android.basic.lesson10;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class MainHelloDatePicker extends Activity {
//准备公用属性
private TextView dateDisplay;
private Button pickDate;
private int mYear;
private int mMonth;
private int mDay;
//准备对话框Id
static final int DATE_DIALOG_ID = 0;
//准备日期设置监听器
private OnDateSetListener dsl = new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear =year;
mMonth= monthOfYear;
mDay= dayOfMonth;
dateDisplay.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
}
};
//重写创建对话框方法
@Override
protected Dialog onCreateDialog(int id){
switch(id){
case DATE_DIALOG_ID:
//把Activity上下文、日期设置监听器、以及日期的年月日都作为参数传给那个新成立的对话框组件
return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
}
return null;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//得到当前日期
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//获取xml中的组件
dateDisplay= (TextView)findViewById(R.id.dateDisplay);
pickDate = (Button)findViewById(R.id.pickDate);
//给日期显示组件一个初始值
dateDisplay.setText(mYear+"-"+(mMonth+1)+"-"+mDay);
//给按钮绑定点击监听器
pickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
}