Android DatePicker控件的使用


Android 创建DatePickerDialog的步骤:

1、申明一个监听器,使用匿名内部类:

DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.
          OnDateSetListener() {    
     @Override
     public void onDateSet(DatePicker view, int year, int monthOfYear,
       int dayOfMonth) {
      System.out.println(year + ":" + monthOfYear + ":" + dayOfMonth);
     }
  };

2、复写Activity类的protected Dialog onCreateDialog(int id)方法

@Override
 protected Dialog onCreateDialog(int id) {
  switch (id) {
  case DATE_PICKER_ID:
   return new DatePickerDialog(this, onDateSetListener, 2011, 8, 26);
  }
  return null;
 }

3、在需要显示日期的时候调用showDialog(DATE_PICKER_ID)方法

 

例子:

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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/textView"
 />
<Button 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button"
    android:text="显示日期"
    />
</LinearLayout>

 

java代码:

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;
import android.widget.TextView;

public class DatePickerActivity extends Activity {
 
 private static final int DATE_PICKER_ID = 1;
 private Button button = null;
 private TextView tv = null;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv = (TextView) findViewById(R.id.textView);
 
  button = (Button) findViewById(R.id.button);
  button.setOnClickListener(new View.OnClickListener() {
  
   @Override
   public void onClick(View v) {
    showDialog(DATE_PICKER_ID);//此方法用于显示DatePickerDialog
   }
  });
 }

 //监听器,监听用户点下DatePickerDialog的set按钮时,所设置的年月日
 private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
  @Override
  public void onDateSet(DatePicker view, int year, int monthOfYear,
    int dayOfMonth) {
   tv.setText(year + ":" + monthOfYear + ":" + dayOfMonth);
  }
 };

 @Override
 protected Dialog onCreateDialog(int id) {
  switch (id) {
  case DATE_PICKER_ID:
   return new DatePickerDialog(this, onDateSetListener, 2011, 8, 26);
  }
  return null;
 }
}

更详细的请参看google api

相关内容