简体   繁体   English

从类中调用一个活动的方法(UNKNOWN)

[英]Call a method of an activity(UNKNOWN) from a class

I want to call a method which is defined in activityA, activityB and activityC from a non-activity class. 我想从非活动类中调用在活动A,活动B和活动C中定义的方法。 I want to call a method of ONLY any one of the activities. 我只想调用任何一种活动的方法。 eg activity.method(), where activity is either activityA or activityB or activityC. 例如activity.method(),其中activity是activityA或activityB或activityC。

((Object) this.context)).method();

In above line I need to specify an Object of an activity. 在上面的行中,我需要指定一个活动的Object How can I determine the the object at run time where I have activity's Context? 如何在运行时确定具有活动上下文的对象?

Note : In real, I have such 10-15 activities. 注意:实际上,我有10到15次这样的活动。

Here's a suggestion : 这是一个建议:

  1. Create an interface with your "method()" signature. 用“ method()”签名创建一个接口。
  2. Let all the activities implement that interface. 让所有活动实现该接口。
  3. Once getting the context, you could typecast your activity to that interface and call the "method()". 获得上下文后,您可以将活动类型转换到该接口,然后调用“ method()”。
  4. Do remember, perform the typecast in a try-catch block, so that if in case you get to a scenario where you try to call the method on an activity which doesn't implemented the interface, you can handle the TypeCastException safely. 请记住,请在try-catch块中执行类型转换,以防万一您遇到在未实现该接口的活动上尝试调用该方法的情况,则可以安全地处理TypeCastException。

Hope this helps. 希望这可以帮助。

Below code might help you 下面的代码可能会帮助您

if(context instanceof ActivityA)
((ActivityA) this.context)).method();
else if(context instanceof ActivityB)
((ActivityB) this.context)).method();
else if(context instanceof ActivityC)
((ActivityC) this.context)).method();

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

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