範例內容跟 Android Developer 官方的範例其實有點類似
不過我個人傾向的事件寫法是在別的地方寫好 function
然後在設定 onClick 之類的事件時再指定到我寫好的 function
官方範例用下面這種寫法我覺得會讓程式碼很亂....
pucliv onCreate() {
...
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
...
}同樣的語法我會寫成下面這樣,把事件的函式內容額外放...
public void onCreate() {
...
mPickDate.setOnClickListener(mPickDateOnClick);
...
}
private View.OnClickListener mPickDateOnClick = new View.OnClickListener () {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
}以下是完整的程式碼:
import java.util.Calendar;
import java.util.Locale;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
public class NewOilRecord extends Activity {
private int currentYear;
private int currentMonth;
private int currentDay;
private Button dateSetButton;
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.new_oil_record);
this.findViews(); // 取得 views
Locale.setDefault(Locale.TAIWAN); // 設定地區
// 設定今天的日期
Calendar cal = Calendar.getInstance();
this.currentYear = cal.get(Calendar.YEAR);
this.currentMonth = cal.get(Calendar.MONTH);
this.currentDay = cal.get(Calendar.DAY_OF_MONTH);
updateDateOfButton(R.id.addOilDateButton, this.currentYear, this.currentMonth, this.currentDay);
// 設定 onClick 事件
this.dateSetButton.setOnClickListener(dateSetButtonClick);
}
private void updateDateOfButton (int viewId, int year, int month, int day) {
this.dateSetButton.append(year+"/"+month+"/"+day);
}
// ------------------------------ //
// ----------- events ----------- //
// ------------------------------ //
// 當 DatePicker 對話框的 Set 按鈕被按下時的動作
private DatePickerDialog.OnDateSetListener addOilDateSet = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker picker, int year, int month, int day) {
// 更新按鈕上顯示的日期
updateDateOfButton(R.id.addOilAmount, year, ++month, day);
}
};
// 當顯示日期的按鈕被按下時的動作
private View.OnClickListener dateSetButtonClick = new View.OnClickListener() {
public void onClick(View v) {
// 呼叫內建函式顯示出對話框
showDialog(R.id.addOilDateButton);
}
};
// 當 showDialog 被呼叫時的動作
public Dialog onCreateDialog (int id) {
switch (id) {
case R.id.addOilDateButton:
// 若是 addOilDateButton 按鈕被按下,則建立一個 DatePicker 的對話框,並指定預設的日期
return new DatePickerDialog(this, this.addOilDateSet, this.currentYear, this.currentMonth, this.currentDay);
}
return null;
}
// ---------------------------------- //
// ----------- find views ----------- //
// ---------------------------------- //
private void findViews () {
this.dateSetButton = (Button) this.findViewById(R.id.addOilDateButton);
}
}其中有一行 Locale.setDefault(Locale.TAIWAN); 意思是設定程式的位置,會影響到 DatePicker 的顯示方式~。
沒有留言:
張貼留言