"this" keyword meaning in Android
Solution 1
As shown in the documentation here, the RelativeLayout
constructor takes in an instance of Context
. I am assuming you are calling that code in an activity, probably in the onStart
method. If this is the case, the this
keyword refers to the current instance of the activity. In android, Activities extend the ContextWrapper
class, making them a subclass of the Context class and therefore passable to the RelativeLayout
and Button
constructor.
The this
keyword refers to the current instance of the class that holds the method containing the constructor that you are calling.
Solution 2
this
refers to the instance of class that this is code is in so for example:
public class Foo {
private string bar = "bar";
public Foo(string bar)
{
this.bar // <-- refers to global bar. Not the bar from constructor.
}
}
In your case this
requires to by of type of the parameter that RelativeLayout
requires, so your class probably must be extended by something that RelativeLayout
requires.
Nav Sandhu
Updated on June 28, 2022Comments
-
Nav Sandhu almost 2 years
I am a beginner in Android Development. The
this
keyword always makes me confused when used in any constructor. Can someone please explain to me what does it mean?RelativeLayout ob = new RelativeLayout(this); Button btn = new Button(this);
What does
this
mean in the previous constructors? What is it referring to?