Android-如何建立建立2按鈕,選取日期+時間(DatePickerDialog、TimePickerDialog)到editText:
Android-如何建立建立2按鈕,選取日期+時間(DatePickerDialog、TimePickerDialog)到editText:
注意:整個事件程式碼都必須放在
onCreate()
{
}
下面
……….
範例:
import android.widget.*;
import android.view.*;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//
button1 Date
日期 事件處理程序
public
void button1_Click(View view) {
showDialog(0);
}
//
button2 Time
時間 事件處理程序
public
void button2_Click(View view) {
showDialog(1);
}
Calendar
dt = Calendar.getInstance();
protected
Dialog onCreateDialog(int id) {
switch (id) {
case 0: // 傳回 日期
DatePickerDialog對話方塊
DatePickerDialog dDialog = new
DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int
year,
int monthOfYear, int dayOfMonth) {
//程式碼寫在這裡
//年=year, 月=monthOfYear+1, 日=dayOfMonth
}
}, dt.get(Calendar.YEAR),
dt.get(Calendar.MONTH),
dt.get(Calendar.DAY_OF_MONTH));
return dDialog;
case 1: // 傳回TimePickerDialog對話方塊
TimePickerDialog tDialog = new
TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view,
int hourOfDay, int minute) {
//程式碼寫在這裡
//時=hourOfDay, 分=minute
}
},
dt.get(Calendar.HOUR),dt.get(Calendar.MINUTE),true);
return tDialog;
}
return null;
} //
end of Dialog onCreateDialog()