Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Toast moves around on screen

My android app displays several Toast messages. I recently installed it on a Galaxy S6, running Android 5.1.1 and noticed that the messages are displayed initially around the center of the screen, then they move to proper position (near bottom, if no Gravity is specified), then back to the initial position before fading away.

Context context = getApplicationContext();
String newMsg = getString(R.string.wild_card_msg);
Toast mToast = Toast.makeText(context, newMsg, Toast.LENGTH_LONG); 
mToast.setGravity(Gravity.CENTER, 0, 0);
mToast.show(); 

Update:

  • I have upgraded support libraries as well as set compile-sdk and target sdk to the latest API. That did not fix the issue
  • I have removed all .setGravity() calls. No change.
  • I have noticed that Toast messages behave properly at the first execution after installation (be it in USB debug mode or via download from PlayStore), but the issue reoccurs at (all) subsequent runs.
  • I have also discovered that my Toast messages disappear immediately if I touch the screen (anywhere). I thought Toast displays cannot be influenced by user interaction.

Anyone else having this issue, know how to fix it or know a workaround?

Please note that I have accepted Nick's answer, proposing snackBar as a workaround.

like image 277
Dior DNA Avatar asked Feb 05 '16 17:02

Dior DNA


People also ask

Can we change the position of toast message in Android?

Positioning your Toast A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

How do you put toast in the middle of the screen?

toast. setGravity(Gravity. TOP|Gravity. LEFT, 0, 0);


1 Answers

Your question asked for a fix or workaround. The simplest workaround is (in my opinion) also the best option, because it moves you to using the more modern components: Switch to a snackbar.

Simple Snackbar:

//on a fragment you can simply use getView(), otherwise give it the root view of your
//layout so that the snackbar can use it to find context

Snackbar.make(getView(), "The toast text", Snackbar.LENGTH_SHORT).show();

It's in the support design library for compatibility.

This is a snackbar:

enter image description here

And some of the support / design libraries that can be included in gradle are

compile 'com.android.support:design:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.android.support:appcompat-v7:23.1.1'
like image 148
Nick Cardoso Avatar answered Sep 17 '22 10:09

Nick Cardoso