xml文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:id="@+id/datePickerEdit" android:enabled="false"
android:layout_width="200dip" android:layout_height="wrap_content" />
<Button android:id="@+id/datePickerButton" android:text="请选择时间"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
activity代码:
package cn.DatePickerDialog.demo;
import java.text.SimpleDateFormat;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class DatePickerDialogDemoActivity extends Activity {
private Button datePickerButton;
private EditText datePickerEdit;
private int m_year, m_month, m_day;
private Calendar c;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 初始化控件
datePickerEdit = (EditText) findViewById(R.id.datePickerEdit);
datePickerButton = (Button) findViewById(R.id.datePickerButton);
datePickerButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
showDialog(0);
}
});
c = Calendar.getInstance();// 获取日历的实例
m_year = c.get(Calendar.YEAR);// 年
m_month = c.get(Calendar.MONTH);// 月
m_day = c.get(Calendar.DAY_OF_MONTH);// 日
}
protected Dialog onCreateDialog(int id) {
if (id == 0) {
return new DatePickerDialog(this, datePickerButtonListener, m_year,
m_month, m_day);
}
return null;
}
private OnDateSetListener datePickerButtonListener = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// 将当前的设置的时间赋值到文本框中
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, monthOfYear);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
datePickerEdit.setText(df.format(c.getTime()));
}
};
}
项目目录结构: