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)

asked Mar 5, 2015 at 20:03
1
  • If you create only one MainActivity, you can even call onButtonClick(v); Commented Mar 5, 2015 at 20:29

2 Answers 2

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.

answered Mar 5, 2015 at 20:05
Sign up to request clarification or add additional context in comments.

Comments

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.

answered Mar 5, 2015 at 20:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.