【问题标题】:What is the difference between using a Context and Activity in an Android Helper class?在 Android Helper 类中使用 Context 和 Activity 有什么区别?
【发布时间】:2013-08-03 11:10:38
【问题描述】:

我正在使用辅助类,我想知道使用 Acitvity 对象和使用 Context 对象之间的实际区别是什么。

假设我有一个类,并说我在该类中创建了一个辅助对象,如下所示:

Helper h = new Helper(this);

现在我可以像这样设置我的助手类:

public class Helper {
    private Activity a;

    public Helper(Activity a) {
        this.a = a;
    }
}

或者我可以这样做:

public class Helper {
    private Context c;

    public Helper(Context c) {
        this.c = c;
    }
}

我什么时候应该使用哪种方法?有什么好处和坏处?

【问题讨论】:

  • Activity是一个Context,即它扩展了Context。请阅读相关文档。除了通过 Intent 或调用 startActivity 启动 Activity 类之外,您不应创建 Activity 类的实例。因此,没有利弊,因为您不应该使用第一种模式。

标签: android android-activity helper android-context


【解决方案1】:

使用:

public Helper(Activity a) {
        this.a = a;
    }

比使用更具体:

public Helper(Context c) {
        this.c = c;
    }

表示(例如),如果你打电话给Helper(MainActivity); 如果您有两个“具有不同返回类型!”的构造函数,它将首先引用Helper(Activity a)。 . 如同: Class(Object o)Class(String s) 调用Class(null) 将导致Class(String s) 而不是Class(Object o) 的响应

Context 是基础对象,因此每个 Activity 都扩展了 Context

java.lang.Object
  ↳ android.content.Context
      ↳ android.content.ContextWrapper
          ↳ android.view.ContextThemeWrapper
              ↳ android.app.Activity

Documentation

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2021-09-11
    相关资源
    最近更新 更多