Reputation: 373
When a new object is made, it often goes:
TextView textView = new TextView(this)
Here, should we always use "this" pointer (an instance of an Activity, normally) as the Context of TextView? For me it seems that any Context would work in many circumstances, such as the following method.
TextView textView = new TextView(this);
textView.setTextSize(textSize);
textView.setTextColor(textColor);
textView.setText(text);
tableRow.addView(textView);
And my assertion is, as I am not adopting any resources, any Context could replace "this." (I assume it is wrong.) Why should we use "this" instead of any other Contexts?
Upvotes: 0
Views: 71
Reputation: 1006799
Here, should we always use "this" pointer (an instance of an Activity, normally) as the Context of TextView?
Occasionally, there is a better choice, but that's usually in obvious circumstances:
You are using Presentation
to route stuff to an external display, and so you use the Context
associated with that Display
You are writing an InputMethodService
and need to return the View
in onCreateInputView()
You are writing a DreamService
and need to call setContentView()
and choose to create your widgets in Java code rather than use a layout
Etc.
I am not adopting any resources
Your code is not. Your app is, in the form of framework classes accessing style/theme resources for your activity (or app).
The blog post by Dave Smith in laalto's comment is an excellent starting point for choosing the right Context
for the right situation.
Upvotes: 2