手持式裝置之隨身照護應用 Android開發環境設定 鐘國家 老師
Date Picker
Use the DatePicker widget, which allows the user to select the month, day, and year, in a familiar interface.
↳android.view.ViewGroup ↳android.widget.FrameLayout Date Picker java.lang.Object ↳android.view.View ↳android.view.ViewGroup ↳android.widget.FrameLayout ↳android.widget.DatePicker
Start a new project named Date_ex1.
Open the res/layout/main.xml file and insert widgets
請跟著版面調整長寬高的設定:
長寬高設定也可以在 main 裡頭改:
Open Date_ex1.java and add the following members to the class:
宣告所使用的元件 public class Date_ex1 extends Activity { public void onCreate(Bundle savedInstanceState) { 宣告所使用的元件
按下Button後想要做的動做? 使用 setOnClickListener() 監聽Button是否動作 date_button.setOnClickListener(new View.OnClickListener() { // 宣告控制項目 與 更改 }
控制項目 設定: 請善用Alt + / 找到你要的函數 // .setText 是顯示文字的語法 // “ ” 是顯示文字 // “ ” 是顯示文字 // + 是字串的連結
動態顯示 日期
public class date_ex1_1 extends Activity { // 宣告 之後需要的變數 // 宣告 之後需要的變數 @Override public void onCreate(Bundle savedInstanceState) {
顯示目前的時間 使用 Calendar 函數 ; 取值 .get()
findViewByID 自訂的變數對應到 main 裡的ID updateDisplay() 為自訂函數 最後再寫內容
.init() 為設定初始化數據 指定對應的變數做更新
副程式 updateDisplay()
DIALOGE 對話視窗顯示
Set Button TextView Change Button 1. showDialog(int) 2. onCreateDialog(int) Set Button DatePickerDialog .OnDateSetListener TextView
動作流程解釋 First, the content is set to the main.xml layout. Then the TextView and Button elements are captured from the layout withfindViewById(int). A new View.OnClickListener is created for the Button, so that when it is clicked, it will callshowDialog(int), passing the unique integer ID for the date picker dialog. Using showDialog(int) allows the Activity to manage the life-cycle of the dialog and will call the onCreateDialog(int) callback method to request the Dialog that should be displayed (which you'll define later). After the on-click listener is set, a new Calendar is created and the current year, month and day are acquired. Finally, the private updateDisplay() method is called in order to fill the TextView with the current date.
Button 按下後的功能: // showDailog(); Date_Dialog_ID 需要宣告 change_b.setOnClickListener(new View.OnClickListener() { //@Override public void onClick(View v) { showDialog(Date_Dialog_ID); } }); Date_Dialog_ID 需要宣告
the callback received when the user "sets” (Button) the date in the dialog, so we need initialize the a new DatePickerDialog.OnDateSetListener as a member in the class // .onDateSetListener 將變數對應在 updateDisplay;
Now add the onCreateDialog(int) callback method to the class:
完整程式碼
END