DatePickerDialog的使用

来源:互联网 发布:西安爱知中学官网网站 编辑:程序博客网 时间:2024/04/30 08:15
Android应用中,日期控件有DatePicker和DatePickerDialog,二者作用基本一样。DatePickerDialog的使用要稍微复杂一点,它是以弹出式对话框形式出现的,并需要实现OnDateSetListener 接口(主要是 onDateSet 方法)。

1、Layout

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:background="@drawable/top"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    >

<TextView android:layout_width="wrap_content"

android:layout_height="wrap_content" android:text="查询日期:"

android:textSize="18sp" />

<TextView android:id="@+scanbycol/tvDate"

android:layout_width="wrap_content" android:layout_height="wrap_content"

android:layout_alignParentTop="true"/>

<Button android:id="@+scanbycol/btnDatePicker" android:text="编辑"

android:layout_toRightOf="@scanbycol/tvDate" android:layout_width="wrap_content"

android:layout_height="wrap_content" />

</RelativeLayout>

我们在xml中,加入了两个textview和一个button。第2个textview显示日期,button用于弹出DatePickerDialog,当用户在DatePickerDialog中修改了日期,则textview接收修改后的日期。

2、Activity

首先,实现OnDateSetListener(其中的onDateSet方法):

//日期选择对话框的DateSet事件监听器

privateDatePickerDialog.OnDateSetListener listener=new DatePickerDialog.OnDateSetListener(){  //

@Override

public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {

cal.set(Calendar.YEAR, arg1);

cal.set(Calendar.MONTH, arg2);

cal.set(Calendar.DAY_OF_MONTH, arg3);

updateDate();

}

};

//DatePickerDialog关闭,更新日期显示

private void updateDate(){

df=new SimpleDateFormat("yyyy-MM-dd");

tvDate.setText(df.format(cal.getTime()));

}

这样,当DatePickerDialog中的日期被改变后,textview中的日期也做相应改变。

接下来,在onCreate方法中,绑定button的onClickListener:

//选择日期按钮

btnDate=(Button)findViewById(R.scanbycol.btnDatePicker);

btnDate.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View v) {

//构建一个DatePickerDialog并显示

new DatePickerDialog(ScanByColActivity.this,

listener,

cal.get(Calendar.YEAR),

cal.get(Calendar.MONTH),

cal.get(Calendar.DAY_OF_MONTH)

).show();

         }

});

这样,当点击button后,会构造一个DatePickerDialog对话框并显示给用户。

整个效果如下图:

 

原创粉丝点击