Retrieve and set data from DialogFragment (DatePicker)

前端 未结 4 692
闹比i
闹比i 2020-12-18 12:44

My DialogFragment class is invoked when I press a button on a activity. I want the date set through this DialogFragment to be displayed on the buttons text. FindViewById re

4条回答
  •  醉话见心
    2020-12-18 13:25

    here's a good pattern to follow:

    1. create a listener interface in your dialog to handle the relevant button presses in the dialog
    2. implement it in the starting activity
    3. when the user presses "okay" or "cancel", call the listener methods
    4. do whatever you need to do in the impl of the listener to update the activity's view

    something like,

    class MyDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
      static interface Listener {
        void onOkay(MyObject result);
        void onCancel();
      }
      ...
    
      @Override
      public Dialog onCreateDialog(Bundle savedInstanceState) {
        ...
    
        // set this as a listener for ok / cancel buttons
        return new AlertDialog.Builder(activity)...whatever...
            .setPositiveButton(R.string.ok, this)
            .setNegativeButton(R.string.cancel, this).create();
      }
    
      @Override
      public void onClick(DialogInterface dialog, int which) {
          if (which == DialogInterface.BUTTON_POSITIVE) {
              if (getActivity() instanceof Listener) {
                  ((Listener)getActivity()).onOkay(...);
              }
          } else {
              if (getActivity() instanceof Listener) {
                  ((Listener)getActivity()).onCancel();
              }
          }
      }
    }
    
    class MyActivity extends Activity implements MyDialogFragment.Listener {
      ...
      @Override
      public void onOkay(MyObject result) {
        // update activity view here with result
      }
    
      @Override
      public void onCancel() {
        // anything?
      }
    }
    

    if your case, the "result" passed into the onOkay() method would be the Date object picked by the user in the dialog.

提交回复
热议问题