从片段显示对话框? [英] Show dialog from fragment?

查看:30
本文介绍了从片段显示对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些需要显示常规对话框的片段.在这些对话框中,用户可以选择是/否答案,然后片段应该相应地表现.

I have some fragments that need to show a regular dialog. On these dialogs the user can choose a yes/no answer, and then the fragment should behave accordingly.

现在,Fragment 类没有要覆盖的 onCreateDialog() 方法,所以我想我必须在包含 活动.没关系,但是 Activity 需要以某种方式向片段报告选择的答案.我当然可以在这里使用回调模式,因此片段在 Activity 中使用侦听器类注册自己,并且 Activity 会通过该类或类似方式报告答案.

Now, the Fragment class doesn't have an onCreateDialog() method to override, so I guess I have to implement the dialogs outside, in the containing Activity. It's ok, but then the Activity needs to report back the chosen answer somehow to the fragment. I could of course use a callback pattern here, so the fragment registers itself at the Activity with a listener class, and the Activity would report back the answer thru that, or something like that.

但是对于在片段中显示简单"是-否对话框的简单任务来说,这似乎是一团糟.此外,这样我的 Fragment 将不那么独立.

But this seems to be quite a big mess for a simple task as displaying a "simple" yes-no dialog in a fragment. Also, this way my Fragment would be less self-contained.

有没有更简洁的方法来做到这一点?

Is there some cleaner way to do this?

这个问题的答案并没有真正详细解释应该如何使用 DialogFragments 来显示来自 Fragment 的对话框.所以AFAIK,要走的路是:

The answer to this question doesn't really explain in detail how one should use DialogFragments to display dialogs from Fragments. So AFAIK, the way to go is:

  1. 显示一个片段.
  2. 需要时,实例化一个 DialogFragment.
  3. 使用.setTargetFragment()将原始Fragment设置为这个DialogFragment的目标.
  4. 使用原始 Fragment 中的 .show() 显示 DialogFragment.
  5. 当用户在这个 DialogFragment 上选择某个选项时,将这个选择通知原始 Fragment(例如用户单击是"),您可以使用 .getTarget() 获取原始 Fragment 的引用.
  6. 关闭 DialogFragment.
  1. Display a Fragment.
  2. When needed, instantiate a DialogFragment.
  3. Set the original Fragment as the target of this DialogFragment, with .setTargetFragment().
  4. Show the DialogFragment with .show() from the original Fragment.
  5. When the user chooses some option on this DialogFragment, notify the original Fragment about this selection (e.g. the user clicked 'yes'), you can get the reference of the original Fragment with .getTarget().
  6. Dismiss the DialogFragment.

推荐答案

你应该使用 DialogFragmenta> 代替.

You should use a DialogFragment instead.

这篇关于从片段显示对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆