您可以使用DialogFragment代替 Dialog。因为对话框次要于它的活动。当您使用 startActivityForResult() 启动活动时,您的对话框将被关闭
另一个使用回调的例子
创建接口
public interface DialogCallback {
void getResults(String results);
}
创建对话框片段
public class DialogFragment extends DialogFragment {
DialogCallback dialogCallback;
public DialogFragment setCallBack(DialogCallback dialogCallback){
this.dialogCallback = dialogCallback;
return this;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return super.onCreateDialog(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_layout, container, false);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
dialogCallback.getResults("hello");
}
}
在您的活动中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new DialogFragment().setCallBack(dialogCallback).show(getFragmentManager(),"");
}
DialogCallback dialogCallback = new DialogCallback() {
@Override
public void getResults(String results) {
if(results!=null){
Log.e(TAG,results);
}
}
};
输出
当您关闭DialogFragment时,您将在Activity中看到“hello”日志