您好,登錄后才能下訂單哦!
開發中經常會遇見在一個編輯框或者文本框中選擇日期,點擊一個文本框彈出一個日期選擇器的組件,在此基礎上進行選擇,廢話少說,直接上代碼:
先定義兩個常量,后面選擇的時候會用到
private static final int DIALOG = 1 ;
private static final int DIALOG2 = 2 ;
定義點擊事件
View.OnClickListener datatextlist = new TextOnClickListener(DIALOG) ;
View.OnClickListener datatext2list = new Text2OnClickListener(DIALOG2) ;
text.setOnClickListener(datatextlist);
text1.setOnClickListener(datatext2list) ;
定義顯示的對話框以及顯示的日期
public Dialog onCreateDialog(int id){
Calendar calendar = Calendar.getInstance() ;
Dialog dialog = null ;
switch(id){
case 1 :
DatePickerDialog.OnDateSetListener datatextlist = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker picker, int year, int month, int dayOfMonth) {
text.setText(year+"-"+(month+1)+"-"+dayOfMonth) ;
}
};
dialog = new DatePickerDialog(MainActivity.this, datatextlist, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MINUTE), calendar.get(Calendar.DAY_OF_MONTH)) ;
break;
case 2 :
DatePickerDialog.OnDateSetListener datatext2list = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker pick, int year, int month, int dayOfMonth) {
text1.setText(year+"-"+(month+1)+"-"+dayOfMonth) ;
}
};
dialog = new DatePickerDialog(MainActivity.this, datatext2list, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)) ;
break ;
}
return dialog ;
}
以下是實現點擊事件顯示對話框
private class TextOnClickListener implements View.OnClickListener{
private int dialogId = 0; //默認為0則不顯示對話框
public TextOnClickListener(int dialogId) {
this.dialogId = dialogId;
}
@Override
public void onClick(View view) {
showDialog(dialogId);
}
}
private class Text2OnClickListener implements View.OnClickListener{
private int dialogId = 0; //默認為0則不顯示對話框
public Text2OnClickListener(int dialogId) {
this.dialogId = dialogId;
}
@Override
public void onClick(View view) {
showDialog(dialogId);
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。