5.2 Android Basic QuickStart Widgets&Other View Date Picker

Date Picker

日期选择控件,允许你选择月,日,年。

在本教程中,将创建DatePickerDialog 对话框。TextView将更新显示选中的日期。

     

  • 新建项目 HelloDatePicker。
  • 打开res/layout/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="wrap_content"

    android:layout_height="wrap_content"

    >

    <TextView android:id="@+id/dateDisplay"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text=""

    />

    <Button android:id="@+id/pickDate"

    android:layout_width = "wrap_content"

    android:layout_height="wrap_content"

    android:text = "Change the date"/>

    </LinearLayout>

    3. 打开 HelloDatePicker.java增加下面的成员变量到类:

    private TextView mDateDisplay;

    private Button mPickDate;

    private int mYear;

    private int mMonth;

    private int mDay;

    4. 增加下面的代码到onCreate()方法:

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

       

    //capture our ivew elements

    mDateDisplay = (TextView)findViewById(R.id.dateDisplay);

    mPickDate = (Button)findViewById(R.id.pickDate);

       

    // add a click listener to the button

    mPickDate.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    // TODO Auto-generated method stub

    showDialog(DATE_DIALOG_ID);

    }

    });

       

    // GET THE CURENT DATE

    final Calendar c = Calendar.getInstance();

    mYear = c.get(Calendar.YEAR);

    mMonth = c.get(Calendar.MONTH);

    mDay = c.get(Calendar.DAY_OF_MONTH);

       

    //display the current date (this method is below)

    updateDisplay();

    }

         

    5. 增加updateDisplay()方法:

    //updates the date in the TextView

    private void updateDisplay(){

    mDateDisplay.setText(

    new StringBuilder().append(mMonth+1).append("-")

    .append(mDay).append("-")

    .append(mYear).append(" ")

    );

    }

         

    6. 初始化一个DatePickerDialog.OnDateSetLintener 成员。

    private DatePickerDialog.OnDateSetListener mDateSetListener=

    new DatePickerDialog.OnDateSetListener(){

    public void onDateSet(DatePicker view, int year,

    int monthOfYear,int dayOfMonth){

    mYear = year;

    mMonth = monthOfYear;

    mDay = dayOfMonth;

    updateDisplay();

    }

    };

         

    7. 重载OnCreateDialog方法:

    @Override

    protected Dialog onCreateDialog(int id) {

       

    switch(id){

    case DATE_DIALOG_ID:

    return new DatePickerDialog(this,

    mDateSetListener,

    mYear,mMonth,mDay

    );

    }

    return null;

    }

    8. 运行应用程序

         

    author: im@xingquan.org

posted @ 2011-03-25 16:24  敏捷学院  阅读(304)  评论(0编辑  收藏  举报