歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android SDK Tutorials系列 - Hello Views - Date Picker

Android SDK Tutorials系列 - Hello Views - Date Picker

日期:2017/3/1 11:03:06   编辑:Linux編程

Date Picker
可以用DatePicker窗口小部件來選擇日期,用戶可以選擇年月日。

本教程裡,你將創建一個DatePickerDialog對話框,點擊按鈕會彈出一個懸浮的日期選擇器對話框。當用戶設置日期以後,一個TextView會顯示剛設置的日期。

創建一個工程:HelloDatePicker.
打開 res/layout/main.xml 並修改如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:orientation="vertical">
  6. <TextView android:id="@+id/dateDisplay"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:text=""/>
  10. <Button android:id="@+id/pickDate"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:text="Change the date"/>
  14. </LinearLayout>

采用LinearLayout布局,裡面用一個TextView來顯示日期,和一個Button,點擊它會打開DatePickerDialog對話框。

打開HelloDatePicker.java ,添加下列成員變量:

  1. private TextView mDateDisplay;
  2. private Button mPickDate;
  3. private int mYear;
  4. private int mMonth;
  5. private int mDay;
  6. static final int DATE_DIALOG_ID = 0;

第一組變量定義了界面裡的View(TextView、Button)以及日期的年月日。靜態整數DATE_DIALOG_ID 是Dialog的ID,用來創建日期選擇器。

修改onCreate() 方法如下:

  1. protected void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.main);
  4. // capture our View elements
  5. mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
  6. mPickDate = (Button) findViewById(R.id.pickDate);
  7. // add a click listener to the button
  8. mPickDate.setOnClickListener(new View.OnClickListener() {
  9. public void onClick(View v) {
  10. showDialog(DATE_DIALOG_ID);
  11. }
  12. });
  13. // get the current date
  14. final Calendar c = Calendar.getInstance();
  15. mYear = c.get(Calendar.YEAR);
  16. mMonth = c.get(Calendar.MONTH);
  17. mDay = c.get(Calendar.DAY_OF_MONTH);
  18. // display the current date (this method is below)
  19. updateDisplay();
  20. }

首先,加載main.xml布局文件。然後使用findViewById(int)來引用TextView和Button。

然後為Button設置一個 View.OnClickListener點擊事件監聽器,當Button被點擊後,showDialog(int)方法會被調用,該方法創建一個ID為DATE_DIALOG_ID的日期選擇器對話框。

showDialog(int)方法讓當前Activity管理對話框的生命周期,同時調用onCreateDialog(int) (將在下一步定義)回調函數顯示對話框。

在設置點擊事件監聽器以後,創建一個Calendar對象,讀取當前年、月、日。最後,調用updateDisplay() 方法,讓TextView顯示當前日期。

Copyright © Linux教程網 All Rights Reserved