我写了扩展DialogFragment
的类MyWindow
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();
}
});
}
}
我想在MainActivity
中创建MyWindow
(mywindow
(的实例,并执行MainActivity的功能以在myWindow.result
关闭后读取。我尝试直接在MainActivity
中呼叫mywindow.setOnDismissListener
,但该程序无法遵守。我试图添加
@Override
public void onDismiss(final DialogInterface dialog) {
super.onDismiss(dialog);
Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener) {
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
到我的窗口,这仍然不起作用。
有没有办法在 MainActivity 中设置 DialogInterface 的 DismissListener?
编辑:
在MainActivity
,我创建了myWindow
myWindow = new MyWindow();
myWindow.show(getSupportFragmentManager(), "confirm_dialog");
让你的活动实现 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);
}
}
}
试试这个。