What is the difference between this, getContext() and getActivity()?

£可爱£侵袭症+ 提交于 2019-11-28 17:14:10

this - return self reference
getContext() - return Context
getActivity() - return Activity

Context.

Quote from original answer :

As the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

Activity

Activity is a Java code that supports a screen or UI. In other words, building block of the user interface is the activity. Activity class is a pre-defined class in Android and every application which has UI must inherit it to create window. Activity represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.

Note : Activity extends Context. Context not an Activity.

Activity is a subclass of Context, so whenever a context is required, either can be given.

getActivity() is at least a method on Fragment, to get the activity it is attached to.

Whenever a context is needed in an instance method of an activity, you can use this.

A context is needed whenever contextual info is needed, or when stuff needs to be displayed.

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