Why Toast.setGravity() is not working
Asked Answered
J

2

5

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.

Johathan answered 3/10, 2016 at 9:9 Comment(3)
because setGravity dont return Toast type.Accretion
can you please explain it in more detail. and why t.setgravity() works and but version 1 not.Johathan
because makeText return type is Toast, So you can access static methods of Toast class. but setGravity have return type void.Accretion
L
5

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.

Leger answered 3/10, 2016 at 9:36 Comment(0)
M
13

I was just attempting this while trying to do the extended challenge in the book, Android Programming: The Big Nerd Ranch

Then I looked up the official docs and learned it is ignored now.

From the official docs, this is a no-op (no operation) when run on newer Android versions.

These are changes that have occurred since the original post.

gravity.setGravity is no-op

Mariandi answered 10/7, 2021 at 23:43 Comment(0)
L
5

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.

Leger answered 3/10, 2016 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.