-2

I want to know what 'this' means in the below Toast command:

Toast.makeText(MainActivity.this, "msg" ,Toast.Length_long ).show();

If possible could you please explain the whole command.

Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
Aravind D
  • 13
  • 5
  • Just read: https://developer.android.com/guide/topics/ui/notifiers/toasts#java . If you do not know what a context is then you need to read some books/tutorials about it first. – Zun Nov 20 '18 at 10:02
  • `Toast` is an **object**, not a **command**. You lack the fundamentals of OOP. – Phantômaxx Nov 20 '18 at 10:21

3 Answers3

1

In general when you use construct SomeClass.this that means that you are referring to the specific (frequently 'outer' class). In example you can have a code like:

class Apple { 

void outherMethod() {
}

class AppleType {

    void innerMethod(){}
        void method(){ 
            Apple.this.outerMethod();
        this.innerMethod();
    }
 }
 }

Additionally, in this specific case on Android it means that you are using the activity's Context which is provided via MainActivity class.

So the whole command should be read as:

  • Create Toast widget inside context provided by MainActivity
  • It should display some text: "msg"
  • It should be visible for specific time defined by the constant: Toast.Length_long
  • finally, via show() method display it on device.
rsulkowski
  • 26
  • 3
0

'this' means itself.

Toast.makeText(MainActivity.this, "msg" ,Toast.Length_long ).show();

Call the toast method, and the required parameters are 'context', 'toast message' and 'toast duration'.

Finally .show() means make toast to show.

eltoryn7
  • 68
  • 6
  • whether "this" means that the mainactivity is contained within itself – Aravind D Nov 20 '18 at 10:11
  • @AravindD MainActivity.this means MainActivity instance itself. So, the mainactivity.this gets context of activity(in this case - mainactivity) – eltoryn7 Nov 20 '18 at 10:28
0

its clear and you can use it like this

Toast toast =Toast.makeText(this, "msg", duration);
toast.show();

this: context
"msg": your message
duration: Toast.LENGTH_SHORT or Toast.LENGTH_LONG
and you can change position by setting gravity

toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);

this will show toast center screen