简体   繁体   English

取消按钮在android中的datepickerdialog中无法正常工作?

[英]Cancel button is not working properly in datepickerdialog in android?

I'm using datepicker dialog in my app in which i have set min and max date which is working fine. 我在我的应用程序中使用了datepicker对话框,在其中设置了最小和最大日期,效果很好。 The set button sets the selected date in Edit text but the cancel button also works as set button and didn't return the previous save date. 设置按钮可以在“编辑”文本中设置所选日期,但是取消按钮也可以用作设置按钮,并且不会返回上一个保存日期。 Please some one help me in this.Thanks in advance. 请有人帮助我。在此先感谢。

Here is the code: 这是代码:

private String dateToSave;
DatePickerDialog _date = null;

private DatePicker dpResult;

private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 1;

int minYear1 = 1970;
int minMonth1 = 0;//0-january , 1-february , 2-march..
int minDay1 =1;

int minYear = minYear1;
int minMonth = minMonth1;
int minDay = minDay1;

//these are the minimum dates to set Datepicker..
private int year;
private int month;
private int day;   

public String dateOutput=null;


@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_change_profile);
    dobET = (EditText) findViewById(R.id.dobET);

    myCalendar = Calendar.getInstance();
     mYear = myCalendar.get(Calendar.YEAR);
     mMonth = myCalendar.get(Calendar.MONTH);
     mDay = myCalendar.get(Calendar.DAY_OF_MONTH);

     setCurrentDateOnView();

     dobET.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
                 showDialog(DATE_DIALOG_ID);
         }
 });

  public void setCurrentDateOnView() {

    System.out.println("----------setCurrentDateOnView()-----------");



    final Calendar c = Calendar.getInstance();
    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH);

    // set current date into textview


    // set current date into datepicker
    //dpResult.init(year, month, day, null);
}


//this was the main part in program to Restrict the DatePicker Dialog  to only its current date.
@Override
protected Dialog onCreateDialog(int id) {
    System.out.println("----------onCreateDialog()-----------");


    switch (id) {
    case DATE_DIALOG_ID:
            _date =  new DatePickerDialog(this,  date,
                    year, mMonth, mDay){
       @Override
       public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
       {  
           System.out.println("----------onDateChanged()-----------"+mYear+"--"+year);
           System.out.println("----------onDateChanged()-----------"+mMonth+"--"+monthOfYear);
           System.out.println("----------onDateChanged()-----------"+mDay+"--"+dayOfMonth);

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


          /* These lines of commented code used for only setting the maximum date on Date Picker..
           *
           * if (year > mYear && year)
               view.updateDate(mYear, mMonth, mDay);

               if (monthOfYear > mMonth && year == mYear )
               view.updateDate(mYear, mMonth, mDay);

               if (dayOfMonth > mDay && year == mYear && monthOfYear == mMonth)
               view.updateDate(mYear, mMonth, mDay);*/


           //these below lines of code used for setting the maximum as well as minimum dates on Date Picker Dialog..
           if (year < minYear)
               view.updateDate(minYear, minMonth, minDay);

               if (monthOfYear < minMonth && year == minYear  )
               view.updateDate(minYear, minMonth, minDay );



               if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
               view.updateDate(minYear, minMonth, minDay);


               if (year > mYear)
               view.updateDate(mYear, mMonth, mDay);

               if (monthOfYear > mMonth && year == mYear)
               view.updateDate(mYear, mMonth, mDay);

               if (dayOfMonth > mDay && year == mYear && monthOfYear == mMonth)
               view.updateDate(mYear, mMonth, mDay);

              dateOutput = String.format("Date Selected: %02d/%02d/%04d",
                                          dayOfMonth, monthOfYear+1, year);
              myCalendar.set(Calendar.YEAR, year);
              myCalendar.set(Calendar.MONTH, monthOfYear);
              myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);


              updateLabel();
       }

   };     
    }
     return _date;
}
    private void updateLabel() {

    String myFormat = "MM-dd-yyyy"; // In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);


    String myFormat2 = "yyyy-MM-dd"; // In which you need put here
    SimpleDateFormat sdf2 = new SimpleDateFormat(myFormat2, Locale.US);
    dateToSave = sdf2.format(myCalendar.getTime());
    saveDOBPrefEditor.putString("DOB", dateToSave);
    saveDOBPrefEditor.commit();

    dobET.setText(sdf.format(myCalendar.getTime()));
}

I am attaching a code which displays the selected date on button (A date dialog is opend when you click this button and displays selected date on it). 我附上了在按钮上显示所选日期的代码(单击此按钮时将打开一个日期对话框,并在其上显示所选日期)。

Instead of the button, use editText. 代替按钮,使用editText。

The problem is with updateLabel(). 问题出在updateLabel()上。 you should not call inside onDateChange(). 您不应在onDateChange()内部调用。 Because when you change the date, onDateChanged() method executes and even though you dont want to set the date and cancle the dialog, by that time updateLable() will be called. 因为当您更改日期时,onDateChanged()方法会执行,即使您不想设置日期并取消对话框,到那时,都会调用updateLable()。

If the above doesnt work, try using the below code, which works fine for me. 如果上述方法不起作用,请尝试使用以下代码,对我来说很好。

private Button btnChangeDate;

    private int year;
    private int month;
    private int day;

    static final int DATE_DIALOG_ID = 999;

@Override
    protected void onCreate(Bundle savedInstanceState) {

//Date Button Instance
        btnChangeDate = (Button) findViewById(R.id.makepayact_btn_ChangeDate);

        //Date picker Dialog
        setCurrentDateOnView();
        addListenerOnButton();
}

// display current date
    public void setCurrentDateOnView() {
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        // set current date into textView
        btnChangeDate.setText("Select");
    }

    //Button Listener
    public void addListenerOnButton() {

        btnChangeDate = (Button) findViewById(R.id.makepayact_btn_ChangeDate);
        btnChangeDate.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            return new DatePickerDialog(this, datePickerListener, year, month,day);
        }
        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) {

            //getting current date instance
            final Calendar c = Calendar.getInstance();
            int current_year = c.get(Calendar.YEAR);
            int current_month = c.get(Calendar.MONTH);
            int current_day = c.get(Calendar.DAY_OF_MONTH);

            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

// Cheque Date Validation -------> Keep or check your validations here 
            if(year<current_year || (year == current_year && month < current_month) || (month == current_month && year == current_year && day < current_day) ){

                //Display in a Dialog for Error
                AlertDialog.Builder builder = new AlertDialog.Builder(CustomerMgmtActivity_MakePayment.this);
                //Chain together various setter methods to set the dialog characteristics
                builder.setMessage("Cheque date should not be before today.")
                .setTitle("Cheque Date Error!");
                // Add the buttons
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked OK button
                        dialog.cancel();
                    }
                });
                // Get the AlertDialog from create()
                AlertDialog alertdialog = builder.create();
                alertdialog.show();

            }
            else{

                // set selected date into TextView
                btnChangeDate.setText(new StringBuilder().append(day)
                        .append("-").append(month + 1).append("-").append(year)
                        .append(" "));

                act_CheqDate = (new StringBuilder().append(year)
                        .append("-").append(month + 1).append("-").append(day + 1)
                        .append(" ")).toString();
            }


        }
    };

Its because u have used updateLAbel() in the onDateChanged method and in your updateLabel() class, u have set the date in the textview. 这是因为您在onDateChanged方法和您的updateLabel()类中使用了updateLAbel(),所以您已经在textview中设置了日期。 that means that everytime date is changed, updateLabel() is also executed and thus date is also set even if u have not pressed set button. 这意味着每次更改日期时,都会执行updateLabel(),因此即使u尚未按set按钮,日期也将被设置。
Solution: Define your own buttons Cancel and Set. 解决方案:定义自己的按钮“取消”和“设置”。 Then setOnClickListener for Set button and move dobET.setText(sdf.format(myCalendar.getTime())); 然后使用setOnClickListener作为“设置”按钮并移动dobET.setText(sdf.format(myCalendar.getTime()));
this code there 那里的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM