Search code examples
androidandroid-datepickerdatepickerdialog

DatePickerDialog opens more than one time when touches EditText


I am using DatePickerDialog in my application. It is Fragment. Now, Issue is that when I couch on EditText, It open dialog 3 times.

I am using Total 2 DatePickerDialog for 2 different EditText and 2 TimePickerDialog for 2 different EditText here.

My Code :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

((EditText) etIOStartDate).setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub

        new DatePickerDialog(getActivity(), StartDate, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
    return false;
    }
});
}
DatePickerDialog.OnDateSetListener StartDate = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub

            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

            String myFormat = "dd-MM-yyyy";
            SimpleDateFormat sdf = new SimpleDateFormat(myFormat,
                    Locale.getDefault());

            ((EditText) etIOStartDate)
                    .setText(sdf.format(myCalendar.getTime()));
        }
    };

Please help me to solve the problem.


Solution

  • Try this. There are two events Action down and Action up.

    ((EditText) etIOStartDate).setOnTouchListener(new View.OnTouchListener() {
    
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                switch(arg1.getAction())
                {
                case MotionEvent.ACTION_DOWN :
                    new DatePickerDialog(getActivity(), StartDate, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                    break;
                case MotionEvent.ACTION_UP  :
                    break;
    
                }
    
                return true;
            }
        });