【问题标题】:Error in Context in Android?Android中的上下文错误?
【发布时间】:2014-02-06 06:27:26
【问题描述】:

我写了简单的一行代码来获取 android 应用程序的上下文。

除了一项活动的新项目外,别无其他。

我在 onCreate 方法中编写了这段代码。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Context context = getContext();
}

它要求我用 getBaseContext 替换 getContext。

为什么我不能只使用现有的 getContext?

【问题讨论】:

  • 活动中的代码在哪里?
  • 我已经在 OnCreate 方法中写过。
  • 那么就用getApplicationContext()
  • 为了更好的练习使用getApplicationContext()
  • 你应该使用 getApplicationContext()

标签: android android-context


【解决方案1】:

请在android上下文中明确您的理解-

getContext() or View.getContext():返回视图运行的上下文,通过它可以访问当前的主题、资源等。

getApplicationContext() or Activity.getApplicationContext():应用程序上下文与应用程序相关联,并且在整个生命周期中始终相同。

Context.getBaseContext():should not used just use Context 而不是它与 Activity 相关联,并且可能在 Activity 被销毁时被销毁。

请查看this blog-post以避免与android上下文相关的内存泄漏问题。

(您可能会遇到很多,但您需要选择适合您需要的)

【讨论】:

    【解决方案2】:
    【解决方案3】:

    通常有两种类型的类。扩展 ContextWrapper 类(Activity、Service、Application)的和不扩展它的(如 View)。

    如果类扩展了 ContextWrapper,那么您可以将其用作 Context。此类类通常没有 getContext() 方法。 那些不扩展 ContextWrapper 但仍然保存和使用 Context 的类通常会暴露 getContext() 函数。在这种情况下,您不能将其用作上下文。

    而且这两种情况是互斥的。至少我不记得扩展 ContextWrapper 并同时具有 getContext 的类。

    礼貌:@inazaruk

    getContext() is not defined for a class that extends an Activity
    

    【讨论】:

    • 上下文上下文 = View.getContext();又出错了。
    【解决方案4】:

    getContext() 未在 Activity 中定义。它在 View(或 View 子类)中用于获取对封闭上下文(Activity)的引用。
    Get context in Android?
    Difference in context this and getContext()
    http://android.okhelp.cz/get-context-java-android-example/

    【讨论】:

      【解决方案5】:

      上下文为新创建的组件提供有关活动或应用程序的信息。并且更具体地获取您想要的上下文,无论是您的视图/整个活动/您正在尝试获取 ContextWrapper。

      试试这个更多信息 getContext API

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 2013-03-02
        • 2011-03-04
        • 2020-09-17
        相关资源
        最近更新 更多