显示从片段对话?片段

2023-09-12 02:41:27 作者:原谅我碍了你这么久

我有一些片段需要出示定期对话。在这些对话框,用户可以选择是/否的答案,然后该片段应相应的行为。

现在,在片段类没有一个 onCreateDialog()方法重写,所以我想我有外执行的对话框,在含活动。这没关系,但随后的活动需要以某种方式向片段报到所选择的答案。当然,我可以用一个回调格局在这里,所以片段注册自己的活动用监听器类,以及活动将汇报通的答案,或者类似的东西这一点。

不过,这似乎是一个相当大的烂摊子一个简单的任务,在一个片段显示一个该死的是 - 否对话框。此外,这样一来我的片段就会少一些独立的。

有一些干净的方式来做到这一点?

编辑:

在回答这个问题并没有真正具体应如何使用DialogFragments从片段显示的对话框说明。所以AFAIK,要走的路是:

在显示一个片段。 当需要时,实例化一个DialogFragment。 将原来的片段,因为这DialogFragment的目标,用 .setTargetFragment()。 显示从原来的片段.show()的DialogFragment。 当用户选择一些选项在这DialogFragment,通知原片段这个选择(例如:用户点击'是'),就可以得到原始片段与.getTarget()的参考。 关闭该DialogFragment。 解决方案 阿静带你看精彩片段这几个对话太精彩了

您应该使用 DialogFragment 代替。

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.

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.

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

Is there some cleaner way to do this?

Edit:

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:

Display a Fragment. When needed, instantiate a DialogFragment. Set the original Fragment as the target of this DialogFragment, with .setTargetFragment(). Show the DialogFragment with .show() from the original Fragment. 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(). Dismiss the DialogFragment.

解决方案

You should use a DialogFragment instead.