I am new to Android programming. I want to know that in this code what does the this
in
TextView textView = new TextView(this);
this would point to which class or method? I copied this code from here.
I am new to Android programming. I want to know that in this code what does the this
in
TextView textView = new TextView(this);
this would point to which class or method? I copied this code from here.
The reason you need this
when creating a TextView
is because one of the the constructors of TextView
(the one that you're calling) takes a Context
object as a parameter.
That basically means you must give TextView
a Context
in order to create it.
Where do you get this context from? Well, an activity is a kind of context (Activity
is a subclass of Context
)! And you're creating the TextView
in an activity class right? So just use this activity as the context!
Got it? Use this activity as the context for the TextView
! That's why you put this
in there. this
refers to the object that the code is currently running on.
Since this
refers to an object created from the class, you can't use this
in a static method because a the code in a static method does not run on any object.
Another use of this
is in constructors:
class MyClass {
private int a, b;
public MyClass(int a, int b) {
this.a = a;
this.b = b;
}
}
Since the compiler can't know which a
or b
you mean, you must add this
to refer the a
that's in the class.
this
refers to the current object's instance that was invoked or initialized.