TheSquigglyLine
TheSquigglyLine

Reputation: 33

Using "this" as an argument to a constructor

I am working through the tutorials provided by Google for learning how to make Android apps and I don't understand why they pass this as an argument when creating and instance of TextView. Here is the code

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    TextView textView = new TextView(this); //The line in question, why do they use "new TextView(this)
    textView.setTextSize(40);
    textView.setText(message);
    setContentView(textView);

Upvotes: 0

Views: 584

Answers (5)

M A
M A

Reputation: 72844

You should read the Java documentation first since much of Android development requires a strong understanding of the language basics. This link explains the use of this.

this is a reference to the current instance of the class which onCreate belongs to. In this case, it refers to the Activity instance.

The TextView constructor takes a Context object as parameter, and the Activity class itself extends Context.

This way the method onCreate creates a TextView that belongs to this activity.

Upvotes: 2

Grambot
Grambot

Reputation: 4514

The documentation for TextView shows that when you want to call the 1-argument constructor you must pass a reference to a Context object. See here.

What you're doing by using this is passing a reference to the current instance of the class to the constructor. In the case of your code you'd be calling it from an Activity which is a child of the Context class. See here

Upvotes: 0

Thirumalai Parthasarathi
Thirumalai Parthasarathi

Reputation: 4671

The TextView class has many constructors and one of them accepts a parameter of type Context.

The this keyword refers to the current object, So the object is a type of Context.

Upvotes: 0

Mosa
Mosa

Reputation: 393

"This" is the reference of the current object, hence the look at the class which holds the method.

Upvotes: 0

phantom
phantom

Reputation: 1455

As you can see from here the constructor requires a variable of type Context. The TextView needs this so it can understand what's currently going on with the program.

Upvotes: 0

Related Questions