1、main.xml的代码:
< ?xml version="1.0" encoding="utf-8"?>
<LINEARLAYOUT android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<TEXTVIEW android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/dateDisplay" android:textSize="20sp">
</TEXTVIEW>
<BUTTON android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="改变日期" android:id="@+id/pickDate" android:textSize="20sp">
</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);
}
});
}
}
3、运行程序见图片
源文件来自:http://android.yaohuiji.com/archives/390