android - 如何收听 DialogFragment 关闭事件

标签 android android-dialogfragment

我已经实现了一个自定义 DialogFragment,我在我的 postReviewFragment 中的 RatingBar 评分监听器事件中显示它,我想在用户关闭对话框时将我的 RatingBar 评分设置回 0。

在 SO 上搜索我遇到了这些线程,但这些解决方案似乎对我不起作用:

DialogFragment Close Event

Can't use onDismiss() when using custom dialogs

DialogFragment and onDismiss

到目前为止,我使用上述线程尝试过的内容:

在 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() 方法仍然没有启动,我做错了什么?

最佳答案

好的,我设法弄明白了:

  1. 首先确保您已在 DialogFragment 和显示对话框的 Fragment 上实现了 DialogInterface.OnDismissListener 并覆盖了 onDismiss() 方法。

  2. 然后当您显示 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);
    
  3. 在 DialogFraments 的 onDismiss() 方法中,我将评级设置为 0 并将其添加到 intent extra,并将 dialogFragment 中的评级栏设置为用户选择的值。

    Intent i = new Intent()
            .putExtra("rating1", rating);
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
    
  4. 然后我重写 onActivityResult() 方法来读取值,并在关闭时将 fragment 上的 ratingbar 值设置为 0。

这可能不是最好的方法,但它确实有效,如果我发现比此方法更好的方法,我会更新答案。如果我的解释不是很清楚,请道歉,查看下面的线程以获得更详细的解释。

引用文献:How to send data from DialogFragment to a Fragment?

关于android - 如何收听 DialogFragment 关闭事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794476/

相关文章:

android - 以编程方式安装 APK 时出现解析错误

java - 从 Activity 启动 DialogFragment

android - DialogFragment 中的 ViewPager2 内的 EditText 不会显示键盘

java - 不要在 DialogFragment 上再次显示复选框

android - DialogFragment的FragmentScenario,onCreateDialog未调用

java - proguard 解析 android.txt 文件中的异常

java - Android 如何强制检查给定的字符串是否为字母数字

java - 数据绑定(bind) - 找不到 BR 类

android - 如果从 fragment 调用 DialogFragment 抛出 ClassCastException

java - 有没有办法可以将这些语句简化为几行代码?