One of the parameters for Toast.makeText()
method is the context.
And for that parameter, I can see value is given as ActivityName.this
in some Android textbooks.
Shouldn't this be this.xxx
?
One of the parameters for Toast.makeText()
method is the context.
And for that parameter, I can see value is given as ActivityName.this
in some Android textbooks.
Shouldn't this be this.xxx
?
Not always, it depends where you are creating the Toast. If, for example, you creating the toast in the onClick
method of a Button
click listener, this
would be the Button, which cannot provide a context.
ActivityName.this
gets the reference to the object of the enclosing class with that name, if the code is in an nested class. For example, if you write this code inside your Activity
's code:
public void onCreate(Bundle bundle) {
// ...
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() { // An anonymous nested class
@Override
public void onClick(View v) {
Toast.makeText(this, "Example", Toast.LENGTH_SHORT);
// This one causes an error; this is not a Context
Toast.makeText(YourActivity.this, "Example", Toast.LENGTH_SHORT);
// This one works
}
});
}
The first this
now refers to a object of the type OnClickListener
. It is not a Context
, so it's an error. The second one refers to the local YourActivity
, which is an Activity
and so a Context
, so it works.
Not really. If you are inside an inner class of ActivityName
, you call ActivityName.this
. If you are not in an inner class, you just call this
.
The point is to refer to the Activity
and use it as a context.