DatePicker示例

1 布局文件很简单,只有一个Button.如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click here"
     />

</LinearLayout>

2 MainActivity如下:

package cn.com.brave;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
public class DatePickerTest extends Activity {
    private Button button;
    private final static int DatePickerID=1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button=(Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
			  showDialog(DatePickerID);//点击按钮后显示时间对话框			
			}
		});
    }
    
    //监听时间对话框上的set按钮
    DatePickerDialog.OnDateSetListener onDateSetListener=new DatePickerDialog.OnDateSetListener() {		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
			System.out.println("year="+year+", month="+monthOfYear+",day="+dayOfMonth);			
		}
	};
	
	//覆写Activty类的方法protected Dialog onCreateDialog(int id) {}
	//用于创建一个DatePickerDialog
	//注意这里有一个问题:在DatePickerDialog上显示的月份比此处实际设置的月份要大1!!!!!!
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DatePickerID:
			return new DatePickerDialog(this, onDateSetListener, 2012, 8, 5);
		default:
			break;
		}
		return super.onCreateDialog(id);
	}
	
}

你可能感兴趣的:(DatePicker示例)