从DialogFragment接收结果 [英] Receive result from DialogFragment
问题描述
我正在使用 DialogFragments 进行一些操作:从列表中选择项目,输入文本。
I am using DialogFragments for a number of things: choosing item from list, entering text.
将值(即列表中的字符串或项目)返回到调用活动/片段的最佳方法是什么?
What is the best way to return a value (i.e. a string or an item from a list) back to the calling activity/fragment?
目前,我正在进行调用活动,实现 DismissListener
,并给DialogFragment一个对该活动的引用。 Dialog然后在活动中调用 OnDimiss
方法,并且该活动从DialogFragment对象中获取结果。非常混乱,并且在DialogFragment失去对活动的引用时,配置更改(方向更改)不起作用。
Currently I am making the calling activity implement DismissListener
and giving the DialogFragment a reference to the activity. The Dialog then calls the OnDimiss
method in the activity and the activity grabs the result from the DialogFragment object. Very messy and it doesn't work on configuration change (orientation change) as the DialogFragment loses the reference to the activity.
感谢任何帮助。
推荐答案
使用,然后在对话框完成后,可以调用
getTargetFragment()。onActivityResult (getTargetRequestCode(),...)
,并在包含的片段中实现 onActivityResult()
。
Use myDialogFragment.setTargetFragment(this, MY_REQUEST_CODE)
from the place where you show the dialog, and then when your dialog is finished, from it you can call getTargetFragment().onActivityResult(getTargetRequestCode(), ...)
, and implement onActivityResult()
in the containing fragment.
似乎是滥用 onActivityResult()
,特别是因为它不涉及活动。但是我已经看到了谷歌官方的推荐,甚至在api演示。我认为这是添加了 g / setTargetFragment()
。
It seems like an abuse of onActivityResult()
, especially as it doesn't involve activities at all. But I've seen it recommended by official google people, and maybe even in the api demos. I think it's what g/setTargetFragment()
were added for.
这篇关于从DialogFragment接收结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!