【问题标题】:Fragments have "getActivity()". What do additional Activities have that mimics this behavior?片段有“getActivity()”。其他活动有什么模仿这种行为?
【发布时间】:2020-06-18 02:41:50
【问题描述】:

在使用 Java 的 Android 开发中,Fragment 具有“getActivity()”,它将为您提供对 MainActivity 的引用。我想知道是否有一种方法可以获取相同类型的 MainActivity 引用,但来自不同的 Activity,而不是 Fragment。

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

在这个例子中,我试图直观地向您展示我在寻找什么。本质上,填写“????” (希望有意义)

我已经尝试了很多事情并且研究了很多。有很多帖子描述了一些在活动之间传递数据的正确方法以及更多错误的方法,但这不是关于在活动之间传递数据的。它是关于从其他活动中引用 MainActivity。

是否可以从其他活动访问 MainActivity?或者这只是不好的做法?似乎它应该像 getActivity() 来自 Fragment 一样简单,但也许我错过了这个概念。

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 中一直阻碍我的事情是无法引用我需要引用的东西。每一个。单身的。时间。当您可以访问您需要访问的内容时,其他一切通常都非常顺利。 :)

感谢您的帮助和时间。

【问题讨论】:

    标签: android android-fragments android-activity


    【解决方案1】:

    这不是活动的运作方式,不。每个活动都完全独立于其他所有活动,您无法安全地访问任何其他活动。这就是为什么像片段这样存在于单个活动中的抽象很有用,以及为什么推荐使用Single Activity pattern

    【讨论】:

    • 谢谢伊恩。这基本上是我需要确认的。我正在做一个 MainActivity -> Fragment -> Activity。为什么?我不知道,也许是旧教程 :) 我会观看您的视频并尝试从 MainActivity -> Fragment -> Fragment 开始,如果这是它的建议。再次感谢。
    猜你喜欢
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    相关资源
    最近更新 更多