[英]How to create a method which used by 3 Activities
I create methodAbc()
for getting network information. 我创建methodAbc()
来获取网络信息。 Context
is required in this method. 此方法需要Context
。 I want to use this method for 3 Activities. 我想将此方法用于3个活动。
How can I implement it? 我该如何实施?
There is two option right now i can see. 我现在可以看到两种选择。
BaseActivity
which will consist the method .. all the activities
will extend from BaseActivity
创建一个将由方法组成的BaseActivity
..所有activities
将从BaseActivity
扩展 Context
as parameter 只需创建一个将Context
作为参数传递的Util静态方法 You can always access a public
method from any class. 您始终可以从任何类访问public
方法。 You just have to create an instance of that class, and then call the method on that instance. 您只需要创建该类的实例,然后在该实例上调用该方法即可。 For example: 例如:
public void methodAbc(Context c) {
// do stuff
}
and then reference that method like so: 然后像这样引用该方法:
YourClass x = new YourClass(yourClassParameters);
x.methodAbc(yourContext); // yourContext might be getApplicationContext()
That, or you could make the method static
. 这样,或者您可以将方法static
。 Although, you may not be able to make your method static
if it has calls to other non-static
class methods. 虽然你可能无法让你的方法static
,如果它有其他调用non-static
类的方法。 Assuming that it can be made a static
method, though: 假设可以将其设为static
方法,但是:
public static void methodAbc(Context c) {
// do stuff
}
and then you can call it from another class, like this: 然后可以从另一个类中调用它,如下所示:
YourClass.methodAbc(yourContext); // yourContext might be getApplicationContext()
public void myMethod(Context context) {
//etc etc
}
Now from any class just refer to it as MyClass.myMethod(this);
现在,从任何类中只需将其称为MyClass.myMethod(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.