Developer
Developer

Reputation: 6350

Open a DatePickerDialog on Click of EditText takes two clicks

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.

Upvotes: 25

Views: 71124

Answers (20)

user18332215
user18332215

Reputation:

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"

Upvotes: 0

Vikrant Singh Rawat
Vikrant Singh Rawat

Reputation: 109

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....
    }
}

});

Upvotes: 0

harsh patel
harsh patel

Reputation: 39

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" />

Upvotes: 0

Vicentex360
Vicentex360

Reputation: 11

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

register_birthday.setInputType(InputType.TYPE_NULL);
register_birthday.requestFocus();

Upvotes: 0

Ashif
Ashif

Reputation: 471

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" />

Upvotes: 0

Joseph Mathai
Joseph Mathai

Reputation: 11

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"/>

Upvotes: 0

uttam kumar sharma
uttam kumar sharma

Reputation: 21

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

Upvotes: 1

Prakash
Prakash

Reputation: 71

In your xml, set the focusable to false

android:focusable="false"

Upvotes: 6

Mehtab
Mehtab

Reputation: 473

Add this in your EditText

 android:editable="false"
 android:focusable="false"

Upvotes: 1

Harsh Singhal
Harsh Singhal

Reputation: 567

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

Upvotes: 1

Hai Rom
Hai Rom

Reputation: 1811

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

Upvotes: 1

Dey
Dey

Reputation: 901

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

Upvotes: 3

Shafqat Jamil Khan
Shafqat Jamil Khan

Reputation: 1037

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

Upvotes: 3

RatneZ
RatneZ

Reputation: 1188

Just use this in your EditText

    android:focusable="false"

Upvotes: 3

Arun Shankar
Arun Shankar

Reputation: 2593

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

Upvotes: 39

Touseef Ahmed
Touseef Ahmed

Reputation: 57

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

Upvotes: 1

Arun Inbasekaran
Arun Inbasekaran

Reputation: 307

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

Upvotes: 15

Lavekush
Lavekush

Reputation: 6166

Just only do this

//Open the DatePicker dialgo in one click and also hide the soft keyboard.
youEditText.setInputType(InputType.TYPE_NULL);
youEditText.requestFocus();

Upvotes: 5

user3687672
user3687672

Reputation: 81

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

}





}

Upvotes: 8

Kartheek Sarabu
Kartheek Sarabu

Reputation: 3926

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

Upvotes: 2

Related Questions