如何在MainActivity中设置DialogFragment的onDismissListener?

时间:2019-09-11 07:01:30

标签: android android-fragments android-dialogfragment android-dialog

我编写了MyWindow类的DialogFragment

public class MyWindow extends DialogFragment {
    public Button yes;
    public Button cancel;
    public Button no;
    public int result;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.save_layout, container);

        initButton(view);
        return view;
    }

    private void initButton(View view) {
        yes = view.findViewById(R.id.yes_button);
        cancel = view.findViewById(R.id.cancel_button);
        no = view.findViewById(R.id.no_button);

        yes.setOnClickListener(new View.OnClickListener() {//
            @Override
            public void onClick(View view) {
                result = 1;
                dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                result = 0;
                dismiss();
            }
        });

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                result = -1;
                dismiss();
            }
        });
    }
}

我想在MyWindow中创建一个mywindowMainActivity)的实例,并执行MainActivity的功能以在关闭后读取myWindow.result。我尝试直接在mywindow.setOnDismissListener中调用MainActivity,但是无法编译该程序。我试图添加

@Override
public void onDismiss(final DialogInterface dialog) {
    super.onDismiss(dialog);
    Activity activity = getActivity();
    if (activity instanceof DialogInterface.OnDismissListener) {
        ((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
    }
}

到MyWindow,仍然无法使用。

是否可以在MainActivity中设置DialogInterface的onDismissListener?

编辑:

MainActivity中,我用{p>

myWindow

1 个答案:

答案 0 :(得分:1)

使您的Activity实现OnDismissListener

public final class YourActivity extends Activity implements DialogInterface.OnDismissListener {

    @Override
    public void onDismiss(final DialogInterface dialog) {
        //Fragment dialog had been dismissed
    }
}

DialogFragment已经实现了OnDismissListener,只需重写该方法并调用Activity。

public final class DialogFragmentCustom extends DialogFragment {

    ///blah blah

    @Override
    public void onDismiss(final DialogInterface dialog) {
        super.onDismiss(dialog);
        final Activity activity = getActivity();
        if (activity instanceof DialogInterface.OnDismissListener) {
            ((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
        }
    }
}

尝试一下。