我编写了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
中创建一个mywindow
(MainActivity
)的实例,并执行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
答案 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);
}
}
}
尝试一下。