Relativelayout lyt = new Relativelayout(this)
what is 'this' doing out here. is that the 'this' keyword in java,if yes what's happening behind the scenes. i just want how are we using 'this' keyword here
Relativelayout lyt = new Relativelayout(this)
what is 'this' doing out here. is that the 'this' keyword in java,if yes what's happening behind the scenes. i just want how are we using 'this' keyword here
In Java, this
means current object i.e. object you are currently working with.
When you say Relativelayout lyt=new Relativelayout(this)
basically you are passing your current object while creating an object of Relativelayout
(of course as long as Relativelayout
has a contructor which accepts whatever is the type of this
).
As an aside, you cannot use this
in static context.
See below sample code with comments for explanation so it will be very easy for your to understand.
public class Class1 {
public static void main(String[] args) {
new Class1().test(); // see here I couldn't do "Class2 class2 = new Class2(this);" because "this" cannot be used in "static" context, so I had to create an object of Class1
}
private void test() {
Class2 class2 = new Class2(this); // here this means current object of "Class1"
}
}
public class Class2 {
private Class1 class1;
Class2(Class1 _class1){
this.class1 = _class1; // here "this" means the object of Class2.
}
}
And finally for your question about keyword, yes "this" is a keyword in Java, refer JLS specs for complete list (§3.9)
As you can see on the documentation, 'this' is the context. I guess this code line is on a class which extends activity, so 'this' represent the activity in which you want to insert the new layout.
You will need the Context class is when creating a view dynamically in an activity.
For example, you may want to dynamically create a ** RelativeLayout** from code. To do so, you instantiate the ** RelativeLayout** class. The constructor for the RelativeLayout class takes a Context object, and because the Activity class is a subclass of Context, you can use the this keyword to represent the Context object.