将应用程序上下文而不是活动上下文传递给视图
为什么可以使用活动上下文,而我们可以使用应用上下文来加载和访问资源?意味着如果我使用应用程序上下文而不是活动上下文,则不会发生异常,那么为什么要使用活动上下文?
Why use Activity Context while we can use Application Context to load and access resource? Means if I use Application Context instead of Activity Context there is no Exception occur so why use Activity Context?
示例:
在下面的示例中,如果我使用 getApplicationContext()而不是"此"活动 onCreate()内的鼠标指针正常工作,没有任何异常.
In below example if I use getApplicationContext() instead of "this" pointer inside the Activities onCreate() it works fine without any exception.
Button button = new Button(getApplicationContext());
getApplicationContext()
应该与view
一起使用,view
的作用域将超出Activity(例如,当您绑定到服务时来自活动).
getApplicationContext()
should be used with the view
, which will be having scope outside the Activity (An example of it might be when you bind to a Service from an Activity).
但是要像上面定义的那样定义视图(定义一个按钮),则应绝对使用Activity's Context
(MyActivity.this
或简单地this
).
But for Defining Views like as you mentioned above (to define a Button), you should Definitely use Activity's Context
(MyActivity.this
or Simply this
).
其原因是,如果您使用getApplicationContext()
,它将在整个应用程序中有效.但是对于Button,它应该在Activity完成后立即销毁,因此在定义Views
类型时最好使用this
(活动的上下文).
The reason for it is if you use getApplicationContext()
, it will live as longer as the Whole Application lives. But for a Button, it should destroy as soon the Activity finishes, So it is always better to use this
(Activity's Context), when defining such type of Views
.
如果我使用应用程序上下文而不是活动上下文,则没有 例外
if I use Application Context instead of Activity Context there is no Exception
也不例外,因为它们都是有效的上下文.如果您在整个应用程序生命周期中都保持视图生命力,即使您不需要它(这最终会导致内存泄漏),或者您希望在活动结束后立即销毁它,这都是您的责任.
There is no exception because both are valid Contexts. Its upon you that if you keep your view alive for entire application lifetime, even if it is not needed (which would ultimately lead to Memory Leakages), or you want to destroy it with as soon as the Activity finishes.