-4

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?

flx
  • 14,146
  • 11
  • 55
  • 70
user2817836
  • 205
  • 2
  • 6

3 Answers3

1

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.

fasteque
  • 4,309
  • 8
  • 38
  • 50
  • you can not use `this` in click listener only if it is anonymous class..there is several way of implementing listener ..One way is to declare the `android:onClick="click"` attribute to button XML and declare the method `click(View v){//perform the task}`..In this case listener is not a anonymous class – Shakeeb Ayaz Sep 26 '13 at 08:07
  • It was just a possible example to explain why you cannot always use this as context. I was not going to do a lecture about this. – fasteque Sep 26 '13 at 08:14
  • Take it easy .u just mentioned click listener therefore I pointed it out. – Shakeeb Ayaz Sep 26 '13 at 08:18
1

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.

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
0

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.

npace
  • 4,218
  • 1
  • 25
  • 35