Reputation: 11
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,
setOnClickListener
and View.OnClickListener
?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
Reputation: 152927
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
.
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
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