单击EditText打开DatePickerDialog需要两次单击

时间:2013-08-16 06:28:08

标签: android android-layout android-datepicker

我想点击编辑文字打开日历。之后,我想设置用户从编辑文本中的日历中选择的日期。问题是,只有当我第二次点击EditText然后打开日历时。请帮我解决问题(why calendar don't open for the first time)。

EditText XML代码

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

活动代码

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

我不明白我做错了什么。请提出解决方案。

19 个答案:

答案 0 :(得分:33)

我会尽力解决你的问题,但我并不完全确定第一个原因。

  1. 仅在第二次点击时打开日历是因为您使用的是edittext。在第一次单击时,您的编辑文本将获得焦点。然后第二次单击只调用onClickListener。

    如果您不期望手动编辑日期(使用键盘),那么为什么不使用TextView显示所选日期?

  2. 由于您未在代码中设置DateSetListener,因此在editText中未更新日期的问题正在发生。您需要设置它以通知系统已设置日期。 DateChange侦听器仅在您更改日期时返回日期,并且您似乎没有在EditText中设置日期。

  3. 试试这段代码:

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

    在此,我将日期更新为具有ID“tvDate”的TextView。我建议使用TextView而不是EditText并尝试此代码。

    更新

    如果您需要使用EditText并在第一次单击时加载日历,请尝试将onFocusListner设置为editText而不是onClickListner。

    editText.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus) {
               // Show your calender here 
            } else {
               // Hide your calender here
            }
        }
    });
    

答案 1 :(得分:14)

在您的edittext中添加此项,以便在第一次点击时打开日期选择器。  android:focusable="false"

答案 2 :(得分:7)

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

}





}

答案 3 :(得分:4)

只做这个

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

答案 4 :(得分:3)

使用setOnFocusChangeListener而不是OnCLickListner以下代码是我用于同一目的的一个例子。

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

答案 5 :(得分:3)

首先在您的活动中定义这些变量

<div class="top watch-video-position">
  <div class="button-2 watch-video-position">
    <div class="eff-2 watch-video-position"></div>
    <a href="#"> CLICK ME </a>
  </div>
</div>

然后使用这些方法:

1)用于打开DATE选择器模态

    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;

2)用于打开TIME选择器模态

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

也可以在关闭日期选择器后将两种方法结合起来打开时间选择器。

这些功能不需要使用插件

答案 6 :(得分:2)

只需在EditText

中使用它
    android:focusable="false"

答案 7 :(得分:2)

尝试此代码100%正常工作

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

在你的课程中使用PASTE剩余代码

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

加载它以编辑文本

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

答案 8 :(得分:1)

首先,在xml中添加echo -e "あいうえお\nオエウイア" | uni2ascii -q | uniq -c | ascii2uni。 在java代码中,只设置一个事件:

android:focusable="false"

答案 9 :(得分:1)

在EditText中添加

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

答案 10 :(得分:1)

100%工作代码

实施x64

在onCreate implements View.OnClickListener

YourEditText.setOnClickListener(this);

答案 11 :(得分:1)

将其添加到EditText xml文件中:

float

通过这种方式,它将像文本视图一样工作

答案 12 :(得分:0)

在xml中,将focusable设置为false

android:focusable="false"

答案 13 :(得分:0)

尝试这个

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

答案 14 :(得分:0)

感谢Lavekush Agrawal,这对我有用,只需将其写在onCreate方法上

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

答案 15 :(得分:0)

问题是您的编辑文本集中在第一次单击上,而不是在第二次单击上应用了单击事件。因此,您只需要将焦点设置为默认,或者像我在xml中所做的那样,添加一个属性,如下所示:

android:focusableInTouchMode="false"

依次将您的xml替换为下面的内容,然后重试:

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

答案 16 :(得分:0)

如果要在编辑文本中单击打开对话框。请试试这个。

let input = [
  {"pagename": "Homepage", "key": "TITLE_HEADER", "value": "Login"},
  {"pagename": "OTPpage", "key": "NAVIGATION_TITLE", "value": "OTP"},
  {"pagename": "Homepage", "key": "SUB_HEADER", "value": "Mobile number"},
  {"pagename": "OTPpage", "key": "TITLE_HEADER", "value": "Login"},
  {"pagename": "RegisterPage", "key": "USERNAME_FIELD", "value": "User name"},
  {"pagename": "Homepage", "key": "SUB_HEADER2", "value": "emailId"},
  {"pagename": "RegisterPage", "key": "PASSWORD_FIELD", "value": "Password"}
]

const result = input.reduce((accumulator, row) => {
  accumulator[row.pagename] = {...(accumulator[row.pagename] || {}), ...{[row.key]: row.value}};
  return accumulator;
}, {})

console.log(result);

});

答案 17 :(得分:-1)

在layout.xml文件中,添加属性android:focusable=false,这肯定可以工作

答案 18 :(得分:-1)

在XML文件中添加属性android:focusableInTouchMode="false"

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