从 DialogFragment 接收结果 [英] Receive result from DialogFragment

查看:25
本文介绍了从 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.

感谢您的帮助.

推荐答案

Use myDialogFragment.setTargetFragment(this, MY_REQUEST_CODE) 从你显示对话框的地方开始,然后当你的对话框完成时,您可以从中调用 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屋!

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