【基础篇】DatePickerDialog日期控件的基本使用(一)

项目步骤:

       1.首先在Main.xml布局文件中添加一个Button标签,用来点击显示日期控件,Main.xml内容如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     tools:context=".MainActivity" >

    <Button        

android:id="@+id/showDatePickerButton"        

android:layout_width="fill_parent"        

android:layout_height="wrap_content"    

 android:text="点击显示日期控件"/>

</RelativeLayout>

2.在Activity中声明并初始化日期控件,并为Button设置监听器,Activity内容如下:

public class MainActivity extends Activity {  

private Button showDatePickerButton = null;

 //该常量用于标识DatePickerDialog  

private static final int DATE_PICKER_ID = 1;  

@Override  

protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);  

//设置布局文件

 setContentView(R.layout.activity_main);  

//根据id找到布局文件中对应的组件

 showDatePickerButton = (Button)findViewById(R.id.showDatePickerButton);  

//为按钮设置监听器

 showDatePickerButton.setOnClickListener(new ButtonListener());

 }  

 class ButtonListener implements android.view.View.OnClickListener{

  @Override

  public void onClick(View v) {   

 //此方法用于显示DatePickerDialog   

 showDialog(DATE_PICKER_ID);  

 }  

}

 //声明一个监听器,使用匿名内部类

 //监听器,显示年月日  

DatePickerDialog.OnDateSetListener onDateSetListener  = new DatePickerDialog.OnDateSetListener() {  

    @Override  

 public void onDateSet(DatePicker view, int year, int monthOfYear,     int dayOfMonth) {   

 System.out.println(year+"-"+monthOfYear+"-"+dayOfMonth);

  }  

};  

/**   * 初始化日期   */  

@Override

 protected Dialog onCreateDialog(int id) {  

 switch(id){   

//初始化日期

case DATE_PICKER_ID:   return new DatePickerDialog(this, onDateSetListener, 2013, 07, 20);  

 }

  return null;  

}

}

 

posted on 2013-08-08 10:12  土鳖程序员  阅读(1091)  评论(0编辑  收藏  举报

导航