DatePickerDialog的使用

来源:互联网 发布:淘宝代销刷销量怎么刷 编辑:程序博客网 时间:2024/04/30 14:38
 
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 事件监听器

private DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener(){  //@Overridepublic 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(){@Overridepublic 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对话框并显示给用户。

整个效果如下图:

 

分享到: 

原创粉丝点击