英文:
Access a method of the immediate activity in the back-stack
问题
所以情境非常简单。
我有两个活动,A和B。
A是主页,您可以从A转到B。
在Activity A中,有一个名为setupDetails()的私有方法,用于更新缓存的用户信息。
所以在活动B中,当操作完成时,我想调用活动A(也称为父活动)的setupDetails()方法。这样做可能吗?不,我不是在谈论*onActivityResults()*或广播侦听器。我想直接从活动B访问那个方法。我尝试搜索类似的问题,但找不到合适的答案,因此在这里发布出来。
英文:
So the scenario is pretty simple.
I have two activities , A and B.
A is the homepage and you can go to B from A.
In Activity A there is a private method called setupDetails() to update cached user info.
So in activity B when an operation completes , I want to call the setupDetails() method of Activity A (aka parent activity). Is it possible to do so ? No i'm not talking about onActivityResults() or a broadcast listener. I want to directly access that method from Activity B. I tried search for similar questions but could not find an suitable answer hence posting it here.
答案1
得分: 1
在ActivityA
中,创建一个类型为ActivityA
的public static
变量,如下所示:
public static ActivityA instance;
在ActivityA
启动ActivityB
之前,可以将自身的引用存储在这个变量中(例如:instance = this
)。
在ActivityB
中,当您想调用ActivityA
中的方法时,只需在public static
变量上调用该方法,例如:
ActivityA.instance.setupDetails();
这应该基本上可以工作,但也有一些情况下它可能无法正常工作。一个例子是,如果您已经启动了ActivityB
,然后应用程序进入了后台。经过一段时间的不活动后,Android会终止托管应用程序的操作系统进程。当用户返回应用程序时,Android将为应用程序创建一个新的操作系统进程,并且只会实例化ActivityB
。在这种情况下,就没有ActivityA
的实例,因此变量ActivityA.instance
将为null
。为了防止空指针异常(NPE),您可以检查这种情况。
英文:
You can do this, but it is kind of hacky.
In ActivityA
, create a public static
variable of type ActivityA
, like this:
public static ActivityA instance;
Before ActivityA
launches ActivityB
, it can store a reference to itself in the variable (ie: instance = this
).
In ActivityB
, when you want to call the method in ActivityA
, just call the method on the public static
variable, ie:
ActivityA.instance.setupDetails();
This should mostly work, but there are cases where it will not work. One example is if you have launched ActivityB
and then the app goes to the background. After some period of inactivity, Android will kill the OS process hosting the app. When the user returns to the app, Android will create a new OS process for the app and instantiate ONLY ActivityB
. In this case, there is no instance of ActivityA
, so the variable ActivityA.instance
will be null
. To prevent a NPE, you can check for this condition.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论