我有一个托管片段的活动。在那片段中,我打开一个DialogFragment。
在片段中,我调用此函数来显示对话框。请注意,在显示对话框之前,我设置了DialogFragment中定义的接口。
private void showRatingDialog(){
if (getActivity() != null) return;
MyRatingDialog ratingDialog = new MyRatingDialog();
ratingDialog.setOnRatingDialog(new MyRatingDialog.OnRatingDialog() {
// some code
});
ratingDialog.show(getActivity().getSupportFragmentManager(), MyRatingDialog.TAG);
}
我的MyRatingDialog课程:
public class MyRatingDialog extends DialogFragment{
private OnRatingDialog onRatingDialog;
public interface OnRatingDialog{
void onSubmitRating(int rateSelected);
void onCancelRating();
}
public void setOnRatingDialog(OnRatingDialog onRatingDialog) {
this.onRatingDialog = onRatingDialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View layout = getActivity().getLayoutInflater().inflate(R.layout.dialog_rating, null, false);
alertDialog = new AlertDialog.Builder(getActivity()).setView(layout).create();
alertDialog.setCancelable(false);
ratingStarComponent = (RatingStarComponent)layout.findViewById(R.id.rating_star_component);
ratingStarComponent.setOnRateListener(new RatingStarComponent.OnRateListener() {
@Override
public void onRateClickListener(int starRate) {
rate = starRate;
}
});
Button rateButton = (Button)layout.findViewById(R.id.rate);
rateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onRatingDialog!=null) { // this is null after a configuration change
onRatingDialog.onSubmitRating(rate, optionsSelected, commentsEditText.getText().toString());
alertDialog.dismiss();
}
}
});
ImageView closeButton = (ImageView)layout.findViewById(R.id.close);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
return alertDialog;
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
onRatingDialog.onCancelRating();
}
}
问题是在像屏幕旋转或任何其他configurationChange之类的configurationChange之后,onRatingDialog接口为null。 我的问题是在configurationChange之后保存对onRatingDialog接口的引用的最佳方法/最佳实践是什么? 我不想让托管的Activity实现接口,因为我认为对对话框的访问更复杂。 通过执行setRetainInstance(true),对话框在configurationChange之后关闭,那么如何保持对话框可见,保持对接口的引用。
感谢。
答案 0 :(得分:0)
在页面上找到以下代码来实现一个监听器,你的Activity必须实现你在对话框中创建的监听器。 然后将从dialogFragment通知Activity并从Activity中通知相关片段。
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
您还可以下载示例项目here