简体   繁体   中英

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. 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.

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

In above line I need to specify an Object of an activity. 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.

Here's a suggestion :

  1. Create an interface with your "method()" signature.
  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()".
  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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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