When programming on Android, we use context object everywhere (maybe context keyword or this keyword), but I don’t really understand what its purpose.
For example, when we add UI Component such as TextView:
TextView textView = new TextView(this); //this simple line make me headache
setContentView(textView);
The first time I think above line is : this keyword mean: this textView will be assign to current screen. But after that, I see that is a wrong thinking because line setContentView(textView) do what I think.
So, who can explain for me, what purpose when we declare context object in above example. (and others case, if you please, tell me more :D)
thanks 🙂
You will need the
Contextclass is when creating a view dynamically in an activity. For example, you may want to dynamically create aTextViewfrom code. To do so, you instantiate theTextViewclass. The constructor for theTextViewclass takes aContextobject, and because theActivityclass is a subclass ofContext, you can use thethiskeyword to represent theContextobject.