Difference in context this and getContext()

2019-01-21 13:39发布

What is difference between this and getContext(), when I say this I mean this within an Activity.

3条回答
我只想做你的唯一
2楼-- · 2019-01-21 13:43

getContext() is not defined in an Activity. It's used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

查看更多
一夜七次
3楼-- · 2019-01-21 13:46

There is no difference. When you are in an Activity, getContext() will return this. This is because an Activity is a context!

查看更多
We Are One
4楼-- · 2019-01-21 13:55

In general there are two type of classes. Ones that extend ContextWrapper class (Activity, Service, Application) and those that do not extend it (like View).

  1. If class extends ContextWrapper then you can use this as Context. Such classes normally do not have getContext() method.

  2. Those classes that do not extend ContextWrapper but still save and use Context normally expose getContext() function. And you cannot use this as Context in such cases.

And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper and have getContext at the same time.

查看更多
登录 后发表回答