我已经实现了一个自定义 DialogFragment,我在我的 postReviewFragment 中的 RatingBar 评分监听器事件中显示它,我想在用户关闭对话框时将我的 RatingBar 评分设置回 0。
在 SO 上搜索我遇到了这些线程,但这些解决方案似乎对我不起作用:
Can't use onDismiss() when using custom dialogs
到目前为止,我使用上述线程尝试过的内容:
在 postReviewFragment 上实现 DialogInterface.OnDismissListener
并覆盖 onDismiss()
方法
@Override
public void onDismiss(final DialogInterface dialog) {
userRating.setRating(0);
}
同样在 DialogFragment 中,我覆盖了 onDismiss()
方法
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
final Fragment parentFragment = getParentFragment();
if (parentFragment instanceof DialogInterface.OnDismissListener) {
((DialogInterface.OnDismissListener) parentFragment).onDismiss(dialog);
}
}
但是当 dialogFragment 被关闭时 onDismiss()
方法仍然没有启动,我做错了什么?
最佳答案
好的,我设法弄明白了:
首先确保您已在 DialogFragment 和显示对话框的 Fragment 上实现了
DialogInterface.OnDismissListener
并覆盖了 onDismiss() 方法。然后当您显示 DialogFragment 设置目标 fragment 时,我在这里通过 Bundle 将评级传递给 DialogFragment
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager(); PostReviewDialogFragment dialog = new PostReviewDialogFragment(); // optionally pass arguments to the dialog fragment Bundle args = new Bundle(); args.putInt("usersRating", rating); dialog.setArguments(args); dialog.setTargetFragment(RestaurantReviewFragment.this,REVIEW_FRAGMENT); dialog.show(fm, TAG);
在 DialogFraments 的
onDismiss()
方法中,我将评级设置为 0 并将其添加到 intent extra,并将 dialogFragment 中的评级栏设置为用户选择的值。Intent i = new Intent() .putExtra("rating1", rating); getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
然后我重写
onActivityResult()
方法来读取值,并在关闭时将 fragment 上的 ratingbar 值设置为 0。
这可能不是最好的方法,但它确实有效,如果我发现比此方法更好的方法,我会更新答案。如果我的解释不是很清楚,请道歉,查看下面的线程以获得更详细的解释。
关于android - 如何收听 DialogFragment 关闭事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794476/