开发中经常会遇见在一个编辑框或者文本框中选择日期,点击一个文本框弹出一个日期选择器的组件,在此基础上进行选择,废话少说,直接上代码:

    先定义两个常量,后面选择的时候会用到

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); 

        }

}