How to get the result from the DialogFragment in Android?

Refresh

November 2018

Views

363 time

2

My Dialog fragment is like below code.

public class PromoCodeDialogFragment extends BaseDialog implements                                           View.OnClickListener {
private Test mBinding;

private String mHeader;
private String mVehicleNumber;

public static PromoCodeDialogFragment newInstance(String mHeader, String mVehicleNumber) {
    PromoCodeDialogFragment dialog = new PromoCodeDialogFragment();
    dialog.mHeader = mHeader;
    dialog.mVehicleNumber = mVehicleNumber;
    return dialog;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);

    mBinding = DataBindingUtil.inflate(inflater, R.layout.test, container, false);

    mBinding.title.setText(mHeader);
    setCancelable(true);

    mBinding.submit.setOnClickListener(this);
    mBinding.cancel.setOnClickListener(this);

    return mBinding.getRoot();
}

@Override
public void onStart() {
    super.onStart();
    getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.submit:
            submit();

            break;

        case R.id.cancel:
            dismiss();
            break;
    }
}

In here if I pressed the submit button then I have to get the result in my MainFragment class.

I called the DialogFragment calling like this

@Override
public void onClick(View view, int position) {
    SearchVehicleResponse.PromotionDetail promotionDetail = mPromoList.get(position);
    if(hasActivity())
    PromoCodeDialogFragment.newInstance(promotionDetail.promotionOffer, mBinding.vehicleId.getText().toString()).show(getActivity().getSupportFragmentManager(), "promo");
}

Now I need to get the response in the Fragment when I click the submit button inside the PromoCodeDialogFragment.

2 answers

1

Фрагмент класса:

public class MyFragment extends Fragment {
int mStackLevel = 0;
public static final int DIALOG_FRAGMENT = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        mStackLevel = savedInstanceState.getInt("level");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("level", mStackLevel);
}

void showDialog(int type) {

    mStackLevel++;

    FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
    Fragment prev = getActivity().getFragmentManager().findFragmentByTag("dialog");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    switch (type) {

        case DIALOG_FRAGMENT:

            DialogFragment dialogFrag = MyDialogFragment.newInstance(123);
            dialogFrag.setTargetFragment(this, DIALOG_FRAGMENT);
            dialogFrag.show(getFragmentManager().beginTransaction(), "dialog");

            break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case DIALOG_FRAGMENT:

                if (resultCode == Activity.RESULT_OK) {
                    // After Ok code.
                } else if (resultCode == Activity.RESULT_CANCELED){
                    // After Cancel code.
                }

                break;
        }
    }
}

}

DialogFragment класс:

public class MyDialogFragment extends DialogFragment {

public static MyDialogFragment newInstance(int num){

    MyDialogFragment dialogFragment = new MyDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("num", num);
    dialogFragment.setArguments(bundle);

    return dialogFragment;

}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
            .setTitle(R.string.ERROR)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton(R.string.ok_button,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, getActivity().getIntent());
                        }
                    }
            )
            .setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, getActivity().getIntent());
                }
            })
            .create();
}
}

Я надеюсь, что это поможет полный!

1

Вы должны создать интерфейс, как например:

public interface OnSubmitClickListener {
    void onSubmitClicked(WhateverInfo info);
}

После этого добавьте OnSubmitClickListenerв ваш диалог и добавить его в конструктор.

Так что ваш диалог класс выглядит следующим образом:

private String mHeader;
private String mVehicleNumber;
private OnSubmitClickListener listener;

public static PromoCodeDialogFragment newInstance(String mHeader, String mVehicleNumber, OnSubmitClickListener listener) {
    PromoCodeDialogFragment dialog = new PromoCodeDialogFragment(listener);
    dialog.mHeader = mHeader;
    dialog.mVehicleNumber = mVehicleNumber;
    return dialog;
}

public PromoCodeDialogFragment (OnSubmitClickListener listener) {
    this.listener= listener;
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.submit:
            listener.onSubmitClicked(infoSomething);

            break;

        case R.id.cancel:
            dismiss();
            break;
    }

и ваш фрагмент выглядит следующим образом:

PromoCodeDialogFragment.newInstance(promotionDetail.promotionOffer, mBinding.vehicleId.getText().toString(), new OnSubmitClickListener(){
        @Override
        public void onSubmitClicked(WhateverInfo info) {
            //get the info from here
        }
    }).show(getActivity().getSupportFragmentManager(), "promo");