【问题标题】:getBaseContext or getContext? How do they differ? [duplicate]getBaseContext 还是 getContext?它们有何不同? [复制]
【发布时间】:2014-05-25 10:47:32
【问题描述】:

我注意到在我的扩展 View 的类中,要获得屏幕大小,我必须使用 getContext

DisplayMetrics dispM = getContext.getResources().getDisplayMetrics();
int width = dispM.WidthPixels;
int height = dispM.HeightPixels;

如果我想在我的 Activity 中做同样的事情,我必须将 getContext 替换为 getBaseContext。为什么会这样?

【问题讨论】:

  • 您可以在Activity中使用Activity实例本身来查找屏幕大小,不需要getBaseContext(),在ViewgetContext()返回一个Context的实例,您将其作为参数传递给查看在其初始化期间,即new View(Context)...

标签: java android


【解决方案1】:

View.getContext(): 返回当前运行视图的上下文。

getBaseContext(): 是活动上下文本身。即使你可以使用this

【讨论】:

    【解决方案2】:

    getContext() 返回视图当前运行的上下文。活动。

    getBaseContext() : 如果你需要从另一个上下文中访问一个上下文,你可以使用这个

    【讨论】:

      【解决方案3】:

      View.getContext() 通常返回当前Activity的视图上下文。 ContextWrapper.getBaseContext() 在从另一个上下文示例 Activity 中访问 Context 时使用。

      见 - Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-29
        • 2012-05-25
        • 1970-01-01
        • 1970-01-01
        • 2012-01-22
        • 1970-01-01
        • 2010-09-26
        相关资源
        最近更新 更多