Reputation: 1615
I have looked at a lot of android tutorials over the internet. In these tutorials they use the this
context for the context everywhere. I know what this
keyword means in Java, but I can't make equal this, with the this
keyword in Android programming. For example, at AlertDialog.Builder
, on the developer.android.com site, there is only one reference at the parameters to the Context, but I can't learn what this this
means here.
Upvotes: 3
Views: 10809
Reputation: 3055
if you have an Activity you can use this
because:
this
is the current instance of a classso you can use your current Activity as a Context.
Look here for the Acitivty doc
and here for an explanation of this
Upvotes: 12
Reputation: 53657
this
is a reference to the current object
You can use this
to refer to any current instance and any instance of its super class.
If your class extends Activity. It is a case of inheritance. your class is subclass and Activity class is parent class. then you can use this keyword to get instance of Activity beacause Activity class is super class of your class. This is implicit casting
also Activity class Context
as superclass. so you can refer the instance of that class using this keyword.
Thanks
Upvotes: 0
Reputation: 12090
The keyword this
is simply a reference -- within an instance of a class -- to itself.
There are two common uses of "this" in Android. These aren't particular to Android, but are valid in Java in general.
this.getResources()
says to call the getResources()
method on this
instance. The this
portion of it is usually unnecessary and used implicitly.
Foo.this.getResources()
could be called from an inner class. This could be handy if the inner class defines getResources()
also, but you want the version defined in the other class.
Upvotes: 0
Reputation: 114777
Here is another question where they explain Context
. As activities and services extend Context
, the this context is a reference to this activity or service.
Upvotes: 0
Reputation: 13501
If you know "this"
variable.. then u may also know that it holds reference for the current object.. so if some method asks for a Context object you can pass this
variable only when it extends classes like Context or Activity.. Because Activity implements context so obeviously its a Context
Upvotes: 0