简体   繁体   English

如何在自定义对话框类中处理onActivityResult

[英]How to handle onActivityResult in a custom dialog class

I am trying to create a custom dialog class that inherits from Dialog that will allow the user to choose a contact. 我试图创建一个继承自Dialog的自定义对话框类,该类将允许用户选择一个联系人。 I can get the contact choose to show up just fine by using: 我可以使用以下方法选择显示的联系人:

this.getOwnerActivity().startActivityForResult(...);

The problem is that this calls the onActivityResult() on the dialog's parent activity when the user chooses a contact; 问题在于,当用户选择联系人时,这会在对话框的父活动上调用onActivityResult()。 I want to encapsulate the handling of the activity result in the dialog class, not the parent activity. 我想将活动结果的处理封装在对话框类中,而不是父活动中。

This chap asked the same question , but did not receive a viable answer: 这个小伙子问了同样的问题 ,但没有得到可行的答案:

inside Android Dialog, how to setup onActivityResult for startActivityForResult? 在Android对话框中,如何为startActivityForResult设置onActivityResult?

Is this possible? 这可能吗? Seems like a pretty basic thing to want to do, so I would think there is way. 似乎想做的一件很基本的事情,所以我认为有办法。

I could convert the dialog to a whole new activity, but the dialog works very nicely within the context of the app so I would rather not have to resort to that. 我可以将对话框转换为全新的活动,但是该对话框在应用程序的上下文中可以很好地工作,因此我宁愿不必诉诸于此。

The dialog is secondary to its activity. 该对话框是其活动的第二位。 When you start the activity with startActivityForResult() , your dialog gets dismissed (and your activity may get recycled). 当您使用startActivityForResult()启动活动时,对话框将被关闭(活动可能会被回收)。 So when you return to YourActivity.onActivityResult() , the dialog is not active, in fact the original dialog object doesn't exist any more. 因此,当您返回YourActivity.onActivityResult() ,该对话框未处于活动状态,实际上,原来的对话框对象已不存在。 You can instantiate the dialog again, show it, pass the necessary data to it, and have it do something, but that seems like a very bad design. 您可以再次实例化对话框,显示它,将必要的数据传递给它,然后让它执行某些操作,但这似乎是一个非常糟糕的设计。 Instead, process your results in the activity and open a dialog to communicate with the user. 而是在活动中处理结果,然后打开一个对话框与用户进行交流。

You can use DialogFragment instead of Dialog. 您可以使用DialogFragment代替Dialog。 @BlackRider already answered The dialog is secondary to its activity. @BlackRider已回答对话框是其活动的第二项。 When you start the activity with startActivityForResult(), your dialog gets dismissed 当您使用startActivityForResult()启动活动时,对话框将被关闭

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM