2

I'm new to Java and I encountered the following code:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = new Button(this);
        button.setText("Touch That!");

        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.this.onButtonClick(v);
            }
        });

        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rootlayout);
        relativeLayout.addView(button);
    }

    public void onButtonClick(View view){
         //do something when button is clicked.
    }

}

I didn't understand the syntax, View.OnClickListener() c'tor is called and it is followed by {} and overidding method. what does this syntax stand for?

to which object this refers? My guess is the button. but if I'm right why to use MainActivity.this instead of this? (the object that invoked the method)

Day_Dreamer
  • 3,311
  • 7
  • 34
  • 61

2 Answers2

3

This is an anonymous class declaration. It means that you will override some methods inside the class dynamically.

Take a look at this arcticle:

http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

About your second question, MainActivity.this refers to the instance of the Activity you are currently in. If you call only this, it would refer to the actual object. When you call MainActivity.this, you will get the instance of MainActivity you are in, even if there is more activities created. Take a look at Android's activity lifecycle.

What's the difference between this and Activity.this

Hope it helps.

Community
  • 1
  • 1
Laerte
  • 7,013
  • 3
  • 32
  • 50
0

By calling

new View.OnClickListener(){}

you are creating an object implementing interface OnClickListerner that requires you to implement the click method.

Someone can correct if I am wrong.

muasif80
  • 5,586
  • 4
  • 32
  • 45