25

I want to open a Calendar on the click of Edit text. After that I want to set the date which the user selects from the Calendar in the edit text. Problem is that, only when I click on the EditText for the second time then the calendar open. Please help me to resolve the issue(why calendar don't open for the first time).

EditText XML code

<EditText
            android:id="@+id/dateofBirth"
            android:layout_width="290dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="10dp"
            android:maxLines="1"
            android:hint="dd/mm/yyyy" />

Activity Code

public void informationPopUp() {
        final Dialog dialog= new Dialog(MainActivity.this,R.style.Dialog_Fullscreen);
        dialog.setContentView(R.layout.details_dialog); 
        dateofBirth = (EditText)dialog.findViewById(R.id.dateofBirth);

        dialog.show();
         myCalendar = Calendar.getInstance();

       final DatePickerDialog.OnDateSetListener date = 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);
                updateLabel();
            }


        };

        dateofBirth.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(DATE_DIALOG_ID);
              }
        });

    }
     private void updateLabel() {
         String myFormat = "MM/dd/yy"; //In which you need put here
         SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
         dateofBirth.setText(sdf.format(myCalendar.getTime()));
     }

     protected Dialog onCreateDialog(int id) {
            final Calendar now = Calendar.getInstance();

            switch (id) {
            case DATE_DIALOG_ID:
                // set date picker as current date
                DatePickerDialog _date =   new DatePickerDialog(this, date,myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)){
                    @Override

                    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){   

                        if (year > now.get(Calendar.YEAR))

                            view.updateDate(myCalendar
                                    .get(Calendar.YEAR), myCalendar
                                    .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                        if (monthOfYear > now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR))
                            view.updateDate(myCalendar
                                    .get(Calendar.YEAR), myCalendar
                                    .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                        if (dayOfMonth > now.get(Calendar.DAY_OF_MONTH) && year == now.get(Calendar.YEAR) && 
                                monthOfYear == now.get(Calendar.MONTH))
                            view.updateDate(myCalendar
                                    .get(Calendar.YEAR), myCalendar
                                    .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
                            }
                };
                return _date;
            }
            return null;
        } 

I am not understanding what I have done wrong. Please suggest a solution.

Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
Developer
  • 6,292
  • 19
  • 55
  • 115

20 Answers20

39

I'll try to address your problem, but I am not completely sure about the first reason.

  1. The calendar opening only on the second click is because you are using an edittext. On the first click, your Edit Text will get focus. then the second click only calls the onClickListener.

    If you are not looking forward to edit the date set manually (using keyboard), then why not using a TextView to display the selected Date?

  2. The problem with the date not updating in editText is occurring because you are not setting the DateSetListener in your code. You need to set that to notify the system that a Date was set. The DateChange listener only returns the date while you are changing the date, and it doesn't appear that you are setting the date in the EditText.

Try this code:

            Calendar cal = Calendar.getInstance(TimeZone.getDefault());
            DatePickerDialog datePicker = new DatePickerDialog(this,
                R.style.AppBlackTheme,
                datePickerListener,
                cal.get(Calendar.YEAR), 
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH));

            datePicker.setCancelable(false);
            datePicker.setTitle("Select the date");

            return datePicker;
        }
    } catch (Exception e) {
        showMsgDialog("Exception",
            "An error occured while showing Date Picker\n\n"
            + " Error Details:\n" + e.toString(), "OK");
    }
    return null;
}


private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth + 1);
        String day1 = String.valueOf(selectedDay);
        TextView tvDt = (TextView) findViewById(R.id.tvDate);
        tvDt.setText(day1 + "/" + month1 + "/" + year1);
    }
};

In this, I am updating the date to a TextView with the ID "tvDate". I advise using a TextView instead of EditText and try this code.

Update

If you need to use EditText and load the calender in the first click, then try setting an onFocusListner to the editText instead of onClickListner.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus) {
           // Show your calender here 
        } else {
           // Hide your calender here
        }
    }
});
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Arun Shankar
  • 2,603
  • 2
  • 26
  • 36
  • 1
    i got my problem of setting the date.But the edit text is creating the problem .u r saying right that edit text will create the problem of focus .but there will be some way to call the onClickListener on first time – Developer Aug 16 '13 at 07:30
  • Updated the answer. Please check – Arun Shankar Aug 16 '13 at 07:49
  • i want to open the calender on click of Edit text only – Developer Aug 16 '13 at 08:44
  • Then better you replace edittext with TextView and add onClickListener to it. If you keep edittext, then try the code in the update. Please inform the result – Arun Shankar Aug 16 '13 at 10:49
  • Can u help me on this calender functionality http://stackoverflow.com/questions/18272306/set-limit-on-the-datepickerdialog-in-android/18272429?noredirect=1#18272429 – Developer Aug 16 '13 at 11:55
  • To me `datePickerListener` is undefined since it was declared below. I placed modifier `private` but it caused another error. – Compaq LE2202x Dec 19 '13 at 09:02
15

Add this in your edittext to open date picker at first click. android:focusable="false"

Automatico
  • 12,420
  • 9
  • 82
  • 110
Arun Inbasekaran
  • 297
  • 1
  • 3
  • 14
  • This is in my opinion the best answer by far as it is the only non-hack approach. – Automatico Sep 30 '15 at 15:00
  • Even though i have this in my edittext, it wont work. – cafebabe1991 Nov 18 '15 at 18:41
  • Try this code to restrict the keyboard from popping on click of edit text box. edittext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); } }); – Arun Inbasekaran Nov 19 '15 at 08:40
8
public class MainActivity extends Activity  {

 private Calendar cal;
 private int day;
 private int month;
 private int year;
 private EditText et;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     et= (EditText) findViewById(R.id.edittext1);
      cal = Calendar.getInstance();
      day = cal.get(Calendar.DAY_OF_MONTH);
      month = cal.get(Calendar.MONTH);
      year = cal.get(Calendar.YEAR);


     et.setText(day+"/"+month+"/"+"/"+year);



      et.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            DateDialog(); 

        }
    });
     }


public void DateDialog(){

    OnDateSetListener listener=new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
        {

         et.setText(dayOfMonth+"/"+monthOfYear+"/"+year);

        }};

    DatePickerDialog dpDialog=new DatePickerDialog(this, listener, year, month, day);
    dpDialog.show();

}





}
kassak
  • 3,974
  • 1
  • 25
  • 36
user3687672
  • 81
  • 1
  • 1
6

In your xml, set the focusable to false

android:focusable="false"
Agilanbu
  • 2,747
  • 2
  • 28
  • 33
Prakash
  • 71
  • 1
  • 2
5

Just only do this

//Open the DatePicker dialgo in one click and also hide the soft keyboard.
youEditText.setInputType(InputType.TYPE_NULL);
youEditText.requestFocus();
Lavekush Agrawal
  • 6,040
  • 7
  • 52
  • 85
3

Just use this in your EditText

    android:focusable="false"
RatneZ
  • 1,078
  • 9
  • 9
3

use setOnFocusChangeListener instead of OnCLickListner following code is an example which i am using for same purpose.

editText_dob.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus){
                hideSoftKeyboard(RegisterationActivity.this);
                editText_dob.setRawInputType(InputType.TYPE_CLASS_TEXT);
                setDate(editText_dob);
            }
        }
    });
Shafqat Jamil Khan
  • 1,039
  • 1
  • 9
  • 17
3

first define these variables in your activity

    import android.app.AlertDialog;
    import android.app.DatePickerDialog;
    import android.app.TimePickerDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.util.Log;
    import android.view.View;
    import android.widget.DatePicker;
    import android.widget.TimePicker;

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;

public class MainActivity extends Activity  {

    private int mYear, mMonth, mDay, mHour, mMinute;

then uses these methods:

1) for open DATE picker modal

            public void openDatePicker() {
                // Get Current Date
                final Calendar c = Calendar.getInstance();
                mYear  = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay   = c.get(Calendar.DAY_OF_MONTH);
                //launch datepicker modal
                DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                Log.d(APIContanst.LOG_APP, "DATE SELECTED "+dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
                                //PUT YOUR LOGING HERE
                                //UNCOMMENT THIS LINE TO CALL TIMEPICKER
                               //openTimePicker();
                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }

2) for open TIME picker modal

            public void openTimePicker() {
                // Get Current Time
                final Calendar c = Calendar.getInstance();
                mHour            = c.get(Calendar.HOUR_OF_DAY);
                mMinute          = c.get(Calendar.MINUTE);
                //launch timepicker modal
                TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                Log.d(APIContanst.LOG_APP, "TIME SELECTED "+hourOfDay + "-" + minute + "-");
                            //PUT YOUR LOGIC HERE
                            }
                        }, mHour, mMinute, false);
                timePickerDialog.show();
            }

also you can combine the two methods to open the time picker after closing the date picker.

These functions do not need to use a plugin

Dey
  • 842
  • 9
  • 21
2

Try this code 100% works

WRITE THIS IN ONCREATE

et_dob.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showDialog(DATE_DIALOG_ID);
        }

    });
    final Calendar calendar = Calendar.getInstance();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    if (et_dob.getText().toString() != null) {
        try {
            calendar.setTime(df.parse(et_dob.getText().toString()));
        } catch (java.text.ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        SimpleDateFormat month_date = new SimpleDateFormat("MMM");
        month = month_date.format(calendar.getTime());
    } else {
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        SimpleDateFormat month_date = new SimpleDateFormat("MMM");
        month = month_date.format(calendar.getTime());
    }

    if (cal_currentTime.compareTo(calendar) > 0)
        updateDisplay();

AND PASTE REMAINING CODE IN YOUR CLASS

static final int DATE_DIALOG_ID = 1;
private int mYear;
private int mMonth;
private int mDay;
private String month;
private String dateOfBirth;


@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DATE_DIALOG_ID:
        return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
                mDay);
    }
    return null;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {
    case DATE_DIALOG_ID:
        ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
        break;
    }
}

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        mYear = year;
        mMonth = monthOfYear;
        mDay = dayOfMonth;

        String dateSetter = (new StringBuilder().append(mYear).append("-")
                .append(mMonth + 1).append("-").append(mDay).append(""))
                .toString();
        final Calendar cal = Calendar.getInstance();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if (dateSetter != null) {
            try {
                cal.setTime(df.parse(dateSetter));
            } catch (java.text.ParseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            SimpleDateFormat month_date = new SimpleDateFormat("MMM");
            month = month_date.format(cal.getTime());
        }

        if (cal_currentTime.compareTo(cal) > 0)
            updateDisplay();
        else
            Toast.makeText(context, "Choose Proper date format",
                    Toast.LENGTH_SHORT).show();
    }
};

to load it to edit text

private void updateDisplay() {
    dateOfBirth = (new StringBuilder()
            // Month is 0 based so add 1
            .append(mYear).append("-").append(mMonth + 1).append("-")
            .append(mDay).append("")).toString();
    et_dob.setText(new StringBuilder()
            // Month is 0 based so add 1
            .append(mDay).append("-").append(month).append("-")
            .append(mYear));
}
Kartheek Sarabu
  • 3,886
  • 8
  • 33
  • 66
1

Add this to your EditText xml file:

    android:clickable="false" 
    android:cursorVisible="false" 
    android:focusable="false" 
    android:focusableInTouchMode="false">

By this way it will work like a text view

Tristan
  • 3,301
  • 8
  • 22
  • 27
1

the first thing, add android:focusable="false" in xml. In java code, only set an event:

case R.id.edt_d_o_birth: {
            KeyboardUtils.hideSoftKeyboard(this);
            Calendar calendar = Calendar.getInstance(Locale.getDefault());
            DatePickerDialog datePickerDialog = new DatePickerDialog(RegisterActivity.this,
                    new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    //todo       
                }
            },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show();
            break;
        }
Hai Rom
  • 1,751
  • 16
  • 9
1

100 % working code

Implement implements View.OnClickListener

Inside onCreate YourEditText.setOnClickListener(this);

@Override
    public void onClick(View v) {

        if (v == YourEditText) {

            // Get Current Date
            final Calendar c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);


            DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {

                            YourEditText.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

                        }
                    }, mYear, mMonth, mDay);
            datePickerDialog.show();
        }
}
Harsh Singhal
  • 567
  • 4
  • 12
1

Add this in your EditText

 android:editable="false"
 android:focusable="false"
Mehtab
  • 453
  • 5
  • 17
1

In the layout.xml file, add the property android:focusable=false, this will surely work

0

In the XML file add property android:focusableInTouchMode="false" :

 <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusableInTouchMode="false"
        android:hint="Some text"/>
0

try this ones

         <EditText
            android:id="@+id/et_mDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clickable="false"
            android:cursorVisible="false"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:hint="Enter A Date in dd/mm/YYYY "
            android:inputType="date"
            android:padding="8dp" />
Ashif
  • 441
  • 5
  • 12
0

Thanks to Lavekush Agrawal , this works for me, just write this on your onCreate method

register_birthday.setInputType(InputType.TYPE_NULL);
register_birthday.requestFocus();
  • Since this is the same as an answer already given, the best way to validate that answer is by upvoting @Lavekush-Agrawal's existing answer. That helps keep the answer section focused, and has the benefit of also boosting Lavekush's reputation, thus rewarding contributors who are providing useful posts. – Tad Wohlrapp May 01 '20 at 19:15
0

problem is your edit text is get in focus on first click and than on second click it apply click event. so you just need to do is set focus default or as i did it in xml add one attribute as below :

android:focusableInTouchMode="false"

in sort replace your xml with below and try again:

<EditText
        android:id="@+id/dateofBirth"
        android:layout_width="290dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="10dp"
        android:maxLines="1"
    android:focusableInTouchMode="false"
        android:hint="dd/mm/yyyy" />
0

If you want open dialog box in edit text single click. Please try this one.

editTextNmae.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus) {
       // call Date dialog box... 
    } else {
       // Hide Hide dialog box....
    }
}

});

0

As you are using EditText it get focused when you click on it for first time. just add focusable attribute in your xml files as :

android:focusable="false"