Alex Duong
Alex Duong

Reputation: 11

syntax issue regarding to setOnClickListener?

May anyone explain to me this bit of code?

Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    Intent intent = new Intent(MainActivity.this, DetailActivity.class);
    startActivity(intent);
     }
});

In this case, MainActivity and DetailActivity are two classes I have created.

I am kind of confused,

  1. In this case, what are the roles of setOnClickListener and View.OnClickListener?
  2. Within the constructor method of the Intent class, for the context, why can't we just put ".this" but we have to put in MainActivity class in the front? Under what kind of situation can we use ".this"?

Upvotes: 0

Views: 61

Answers (2)

laalto
laalto

Reputation: 152927

  1. setOnClickListener is a method. View.OnClickListener is an interface. The setOnClickListener method takes a View.OnClickListener as an argument. The syntax new Foo() { ... } defines an anonymous inner class instance that implements the interface Foo.

  2. this refers to the instance, which in case of an inner class is the inner class View.OnClickListener instance. You can refer to the outer class instance (an activity which is-a Context) by scoping the reference with the outer class name.

Upvotes: 1

Mohammed Rampurawala
Mohammed Rampurawala

Reputation: 3122

You have to put MainActivity.this because the setOnClickListener is a interface in a View class and it contains a method onClick(View v); , if you will use this instead of MainActivity.this, it will refer to the Context of OnClickListener, when we specify MainActiviy.this it refers to the Context of MainActivity class. This concept is called Shadowing in java.

Upvotes: 0

Related Questions