user12245898
user12245898

Reputation:

Android: Why does a "TextView" object need a reference to an activity as an argument?

The question is in the title

Example :

val textview = TextView(this)

Upvotes: 0

Views: 59

Answers (3)

Animesh Sahu
Animesh Sahu

Reputation: 8106

Why does a “TextView” object need a reference to an activity as an argument?

If you look at the Source Code of Android's View, the constructor takes and stores it in a variable named mContext:

/**
 * The application environment this view lives in.
 * This field should be made private, so it is hidden from the SDK.
 * {@hide}
 */
protected Context mContext;
// ...
public View(Context context) {
    mContext = context;
    // ...
}

That variable is useful for maintenance of its lifecycle, and used in many methods in the View class. As for example, initScrollCache, sendAccessibilityEventInternal, onScrollChanged and many more methods do use them.

Upvotes: 1

AskNilesh
AskNilesh

Reputation: 69709

Why does a “TextView” object need a reference to an activity as an argument?

Because when you want to create a TextView programmatically you need to pass context as an argument

For example val textview = TextView(this)

Here this refers to your current activity.

Upvotes: 0

waqaslam
waqaslam

Reputation: 68187

Views (i.e. TextView) need reference to the Context. Since Activity extends Context class, hence devs usually use this keyword to reference to context and fulfill the argument requirement.

Upvotes: 1

Related Questions