-1
package com.example.sumant.myapplication2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        RelativeLayout myLayout=new RelativeLayout(this);
        Button myButton =new Button(this);
        myLayout.addView(myButton);
        setContentView(myLayout);

    }
}

The "this" variable is as a reference for the current object. But I am not getting as to why it has been used as a parameter in the above piece of code. I am able to decipher that maybe the constructor of RelativeLayout class might be parameterized and we are passing it an object of the same class to initialize the RelativeLayout object. Can someone please elaborate it to me.

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 3
    `RelativeLayout` requires a `Context` as the constructor argument in your usecase, seeing as `AppCompatActivity` IS A `Context` (inheritance) and your `MainActivity` extends this class then the parameter is satisfied. Full inheritance of `AppCompatActivity` - https://developer.android.com/reference/android/support/v7/app/AppCompatActivity – Mark Dec 28 '18 at 11:18

2 Answers2

0

In java "this" variable is as a reference for the current object.

RelativeLayout myLayout=new RelativeLayout(this);

but android these case its constructor parameters it refers the context of activity/fragment

sasikumar
  • 12,540
  • 3
  • 28
  • 48
0

You are invoking this method, public RelativeLayout (Context context) which takes Context as a parameter.

To Understand What is 'Context' on Android? visit here

touhid udoy
  • 4,005
  • 2
  • 18
  • 31