Search code examples
androidandroid-toast

Why Toast.setGravity() is not working


Hello guys I have 2 versions of Toast like this

version 1:

Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).setGravity(Gravity.CENTER,0,0).show();

version 2:

Toast t = Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG);
      t.setGravity(Gravity.CENTER,0,0);
      t.show();

Version 2 works fine but version 1 is not. it gives error cannot resolve method show(). what is going wrong here?

when I write version 1 removing setGravity() method then it works fine

Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).show();

can you guys explain it.


Solution

  • Toast.makeText(this, getString(R.string.back_not_allowed), Toast.LENGTH_SHORT) returns a Toast instance so you can call show() function on it, but Toast.makeText(this, getString(R.string.back_not_allowed), Toast.LENGTH_SHORT).show() returns void so you can't use setGravity(Gravity.CENTER,0,0) over it. This is the reason you have to get the instance of Toast in a variable and then use it.