Trying to set text of EditText from DatePicker DialogFragment

前端 未结 2 1695
梦如初夏
梦如初夏 2020-12-20 06:42

I am simply trying to get the date from a datepicker dialog I created from one of the many android datepicker tutorials I found online. I seem to be going wrong somewhere in

相关标签:
2条回答
  • 2020-12-20 07:03

    I have done this by below lines of code:

    public class DatePickerDialogMy extends DialogFragment {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            DateSetting dateSetting=new DateSetting(getActivity());
            Calendar calendar= Calendar.getInstance();
            int year= calendar.get(calendar.YEAR);
            int month=calendar.get(calendar.MONTH);
            int day=calendar.get(calendar.DAY_OF_MONTH);
            DatePickerDialog dialog;
            dialog=new DatePickerDialog(getActivity(),dateSetting,year,month,day);
            return dialog;
        }
    }
    

    Second Class:

            public class DateSetting implements android.app.DatePickerDialog.OnDateSetListener {
                Context context;
                public DateSetting(Context context){
                    this.context=context;
    
                }
                @Override
                public void onDateSet(DatePicker view, int year, int dateSetting, int dayOfMonth) {
                    Toast.makeText(context, "selected date:" + dateSetting + "/" + dayOfMonth + "/" + year, Toast.LENGTH_LONG).show();
            //        MainActivity.test.setText(String.valueOf(dateSetting));
                    MyActivity.dobEditText.setText(dateSetting+"/"+dayOfMonth+ "/" + year);
                }
            }
    

    How to call:

     DatePickerDialogMy datePickerDialog = new DatePickerDialogMy();
                    datePickerDialog.show(getSupportFragmentManager(), "date_picker");
    
    0 讨论(0)
  • 2020-12-20 07:06

    You need to use an interface to get the data from the datepicker to the caller fragment:

    public interface DateListener {
        void passDate(String date);
    }
    

    Create a member variable called mListener:

    private DateListener mListener;
    

    Override the onAttach & onDetach fragment methods:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (DateListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DateListener");
        }
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    

    Next, implement this interface in the caller fragment and override the passDate method:

    @Override
    public void passDate(String date) {
        // Do something with 'date', yourEditText.setText(date) for the example
    }
    

    And you should be good to go.

    0 讨论(0)
提交回复
热议问题