Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss DatePickerDialog on pressing back button

On my view I have a button which when pressed pops up a DatePickerDialog. The poppedup dialog has a "Done" button. When I press that button the selected date is populated into an EditText box.

Now, when I press the back button (Back button), it still populates the date in the EditText. How do I dismiss the dialog without returning any value from it.

This is code I've got-

The activity which invokes the fragment:

public class TransactionActivity extends FragmentActivity implements iRibbonMenuCallback {        
    .....
    public void selectDate(View view) { 
        // This is the method invoked by the button
        SelectDateFragment newFragment = new SelectDateFragment();
        newFragment.show(getSupportFragmentManager(), "DatePicker");
    }

    public void populateSetDate(int year, int month, int day) {
        // Puts the date in the EditText box
        mEdit = (EditText)findViewById(R.id.DateText);
        mEdit.setText(month+"/"+day+"/"+year);
    }
}

A fragment for the Dialog (based on this page on Android API guides):

public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, yy, mm, dd);
    }

    public void onDateSet(DatePicker view, int yy, int mm, int dd) {
             // Calls a method on the activity which invokes this fragment
         ((TransactionActivity)getActivity()).populateSetDate(yy, mm+1, dd);    

    }
}

There doesn't seem to be a method analogous with onDataSet for handling the case when data was not set.

Is there a way to cancel/dismiss the popped up datepicker without getting it's value?

Thanks.

like image 539
Bharat Avatar asked Mar 08 '13 07:03

Bharat


1 Answers

It looks like there is a bug with Jelybean where the Cancel button isn't working(& hence the back button). This is discussed in Jelly Bean DatePickerDialog --- is there a way to cancel?

David Cesarino, who reported the bug and workaround in the above post, posted his solution here and SO.

cavega slightly modified the above solution to allow initialization of the date in the DatePickerDialog to something other than today's date. Code can be found here. I used his solution and got it to work.

like image 180
Bharat Avatar answered Sep 29 '22 01:09

Bharat