简体   繁体   English

如何创建3个活动所使用的方法

[英]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. 我现在可以看到两种选择。

  1. Create a BaseActivity which will consist the method .. all the activities will extend from BaseActivity 创建一个将由方法组成的BaseActivity ..所有activities将从BaseActivity扩展
  2. Simply create a Util static method passing a 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.

相关问题 我要创建通用的AsyncTask,可用于所有活动以保存图像 - I want to create generic AsyncTask, Which can be used for all activities to save Image 如何创建使用泛型类型 T.class 实例的泛型方法? - How to create generic method which I used an instance of generic type T.class? 如何覆盖父构造函数中使用的方法? - How to override a method which is used in the parent constructor? 如何限制在多个活动中使用的 Android 自定义 ListView 中显示的字符数? - How To Limit The Number of Characters displayed In Android Custom ListView which is used in Multiple activities? 如何创建只能用于测试的方法 - How to create method that could be used only for tests Android Espresso:如何创建可以启动具有不同活动的单独测试类的测试套件? - Android Espresso: How to create test-suite which may launch separate test classes with different activities? 我可以使用许多活动中使用的静态方法生成Toast吗? - Can I generate Toast with a static method used in many Activities? 如何在 Akka runWith() 中创建方法并使用此方法 - How to create method and used this method inside Akka runWith() java,如何关闭在不同方法中使用的语句? - java, how to close statement which is used in different method? 我们如何指定将用于身份验证的方法? - How can we specify a method which will be used to authentication?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM