Difference between getApplicationContext and classname.this

烈酒焚心 提交于 2019-11-27 18:34:39

问题


When I'm using list view and I have a custom Base Adapter class, I get different text color in list view when base adapter is instantiated by getApplicationContext and classname.this. By getApplicationContext I get white text color but classname.this is black. Can anyone explain it for me?


回答1:


Basically they are both instances of Context, but the difference is application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment...

see getApplicationContext

EDIT

In finding your answer it will help you Android Holo Light styling changes depending on chosen context




回答2:


ActivityName.this refers to activity context. getApplicationContext () refers to the application context.

Most of the times it is better to use activity context.

Check the answer provided by commonsware. Has a detail explanation on the topic.

When to call activity context OR application context?

Quote form the above link

Here are reasons why not to use getApplicationContext() wherever you go:

  1. It's not a complete Context, supporting everything that Activity does. Various things you will try to do with this Context will fail, mostly related to the GUI.

  2. It can create memory leaks, if the Context from getApplicationContext() holds onto something created by your calls on it that you don't clean up. With an Activity, if it holds onto something, once the Activity gets garbage collected, everything else flushes out too. The Application object remains for the lifetime of your process.



来源:https://stackoverflow.com/questions/16141369/difference-between-getapplicationcontext-and-classname-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!