How to get data from DialogFragment to a Fragment?

后端 未结 6 1173
独厮守ぢ
独厮守ぢ 2020-11-30 22:13

Imagine, I have FragmentA from which I startDialogFragment (there are EditText in box). How to can I get back the value from the EditTex

6条回答
  •  [愿得一人]
    2020-11-30 22:24

    This method ensures that the calling fragment implements the onChangeListener of the dialog.

    FragmentA (calling fragment):

    MyDialogFragment f = new MyDialogFragment();
    Bundle args = new Bundle();
    args.putString("data", data);
    f.setArguments(args);
    // Set the calling fragment for this dialog.
    f.setTargetFragment(FragmentA.this, 0);
    f.show(getActivity().getSupportFragmentManager(), "MyDialogFragment");
    

    MyDialogFragment:

    import android.support.v4.app.DialogFragment;
    
    public class MyDialogFragment extends DialogFragment {
        public OnChangeListener onChangeListener;
    
        interface OnChangeListener{
            void onChange(Data data);
        }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Get the calling fragment and ensure that it implements onChangeListener.
            try {
                onChangeListener = (OnChangeListener) getTargetFragment();
            } catch (ClassCastException e) {
                throw new ClassCastException(
                    "The calling Fragment must implement MyDialogFragment.onChangeListener");
            }
        }
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            .....
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Send the data to the calling fragment.
                    onChangeListener.onChange(data);
                }
            });
            .....
        }
    }
    

提交回复
热议问题