日期對話框和時間對話框是android開發中使用比較少的一種對話框顯示方式,這裏我們也介紹它們的使用方式。
整體思路:在xml文件中定義兩個button控件,並在activity中設置它們的點擊事件,定義一個Calendar類,初始化年、月、日、小時、分鐘,在第一個點擊事件中,定義一個DatePickerDialog對象,顯示日期對話框並定義它的選擇日期的觸發事件,在第二個點擊事件中,定義一個TimePickerDialog對象,顯示時間對話框並定義它的選擇時間的觸發事件。
MainActivity.java文件:
public class MainActivity extends Activity {
private Button button,button2;
private int year,monthOfYear,dayOfMonth;//初始化年月日
private int hourOfDay,minute;//初始化小時、分鐘
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
// 初始化年月日的日期
Calendar calendar=Calendar.getInstance();
year=calendar.get(Calendar.YEAR);
monthOfYear=calendar.get(Calendar.MONTH);
dayOfMonth=calendar.get(Calendar.DAY_OF_MONTH);
// 初始化小時和分鐘
hourOfDay=calendar.get(Calendar.HOUR_OF_DAY);
minute=calendar.get(Calendar.MINUTE);
// 完成對年月日的初始化
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
DatePickerDialog datePickerDialog=new DatePickerDialog(MainActivity.this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int year, int monthOfYear, int dayOfMonth) {
// 當用戶選擇日期的時候會觸發
// 2013年-4月-5日
String string=year+"年-"+monthOfYear+"月-"+dayOfMonth+"日";
Toast.makeText(MainActivity.this, string, 1).show();
}
}, year, monthOfYear, dayOfMonth);
datePickerDialog.show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TimePickerDialog dialog=new TimePickerDialog(MainActivity.this, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker arg0, int hourOfDay, int minute) {
// TODO Auto-generated method stub
String string=hourOfDay+"時:"+minute+"分";
Toast.makeText(MainActivity.this, string, 1).show();
}
}, hourOfDay, minute, true);//true表示選擇的是24小時
dialog.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}