简体   繁体   English

处理DialogFragment回调的最佳方法是什么?

[英]What is the best way to handle DialogFragment callbacks?

I've been using DialogFragment to handle Dialogs on an app. 我一直在使用DialogFragment处理应用程序上的对话框。

I've read this which gives some examples about how to use it, but it always uses things like: 我读过这篇文章 ,提供了一些有关如何使用它的示例,但它总是使用类似以下内容的东西:

((FragmentAlertDialog)getActivity()).doPositiveClick();
((FragmentAlertDialog)getActivity()).doNegativeClick();

I don't really like this implementation as it obliges a cast to a pre-known Activity so it's not very robust. 我不太喜欢这种实现方式,因为它强制强制转换到一个预先已知的Activity,因此它不是很可靠。

I also know that passing and storing a callback inside the FragmentDialog isn't a good option because if it references an Activity, after rotation for example, that activity could have been destroyed... and the callback is not updated. 我也知道FragmentDialog内传递和存储回调不是一个好选择,因为如果它引用一个Activity,例如在旋转之后,该Activity可能已经被破坏了……并且该回调未更新。

Also updating the callback when an activity passes onResume is also not a very viable option, as it had to know which Dialog is being shown and set a callback related to it making the logic a bit tricky on larger apps. 在活动通过onResume时更新回调也不是一个可行的选择,因为它必须知道显示了哪个Dialog并设置与之相关的回调,这使得大型应用程序的逻辑有些棘手。

So what implementation do you suggest to avoid casts while retaining always the most up-to-date callback? 那么,您建议采用什么实现来避免强制转换,同时始终保留最新的回调?

You've enumerated the reasons why callbacks can't be used, very eloquently. 您已经非常雄辩地列举了无法使用回调的原因。 Unfortunately, I think the cast (or something similar) is unavoidable. 不幸的是,我认为演员表(或类似的东西)是不可避免的。 The whole paradigm is rather awkward, frankly. 坦率地说,整个范例相当尴尬。

You could use an interface, if you plan to share a dialog fragment between multiple activities. 如果计划在多个活动之间共享对话框片段,则可以使用界面。

 ((IXyzDialogHost)GetActivity())->onSomethingHappened()

There's something to be said for that approach, I suppose. 我想对于这种方法要说些什么。 I can't say I've used that approach myself, personally, but thinking about it, I might be tempted to do so moving forward. 我不能说我本人亲自使用过这种方法,但是考虑到这一点,我可能会倾向于这样做。 At least you can enforce a contract on the calling Activity with an appropriate static DialogFragment.Create method, which deals with the setting of the bundle the fragment manager transaction, and other unpleasantries: 至少您可以使用适当的静态DialogFragment.Create方法在调用方Activity上执行合同,该方法处理片段管理器事务的捆绑软件设置以及其他不愉快之处:

 class XyzDialogFragment {
   {
         public static DialogFragment Create(IXyzDialogHost activity, ...)
         {
            ...
         }

   } 

But there's still a cast. 但是仍然有演员表。

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

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