碎片有"getActivity()".其他活动具有哪些模仿此行为的功能?



在使用Java的Android开发中,Fragments有"getActivity((",它会给你对MainActivity的引用。我想知道是否有一种方法可以获得与 MainActivity 完全相同类型的引用,但来自不同的活动,而不是片段。

IE: (Not in code, more of a diagram)
MainActivity - "this"          : MainActivity reference
Fragments    - "getActivity()" : MainActivity reference
Activity 2   - "this"          : Activity 2 reference
Activity 2   - ????            : MainActivity reference
Activity 3   - "this"          : Activity 3 reference
Activity 3   - ????            : MainActivity reference

在此示例中,我试图直观地向您展示我正在寻找的内容。本质上,填写"????"(希望这是有道理的(

我尝试了很多东西,研究了很多。有很多帖子描述了在活动之间传递数据的一些正确方法和更多错误的方法,但这不是关于在活动之间传递数据。它是关于从其他活动中引用主活动。

是否可以从其他活动访问主活动?还是只是不好的做法?看起来它应该像来自片段的getActivity((一样简单,但也许我错过了这个概念。

Things I have tried that have not worked are. 
1. Passing the MainActivity reference itself through an Intent, this fails because Activities are not Parceable. (I can pass parceable data and other variables just fine, but not an Activity)
2. I have tried making the activity a child of MainActivity in the AndroidManifest and as well as adding meta data claiming it is the child. This is help get a non_null return from get getParentActivityIntent(); However, it does not provide any way to get that MainActivity reference from that.
3. I have tried getParent(); This always returns null.
4. I have tried getCallingActivity(); This always returns null.
5. I have tried getApplicationContext(); This doesn't seem to have a way to funnel down to a MainActivity reference.
6. Definitely many more things that aren't worth mentioning or forgotten.

我现在基本上被封锁了 2 天,一直在研究这个,直到我能找到一种方法来获得这个参考。有很多帖子你会认为是相关的,但实际上并没有通过真正的参考,或者直接甚至间接回答我的问题。在Android Java中,总是阻碍我的事情是无法引用我需要引用的东西。每。单。时间。当您可以访问需要访问的内容时,其他所有内容通常都非常顺利。:)

感谢您的帮助和时间。

这不是活动的工作方式,不是。每个活动都完全独立于其他所有活动,您无法安全地访问任何其他活动。这就是为什么存在于单个活动中的抽象(如片段(很有用,以及建议使用单个活动模式的原因。

最新更新