Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Android toasts not aligning properly

I'm simply calling from my Activity:

Toast.makeText(this, "This is a toast", Toast.LENGTH_SHORT).show()

But the result is a text aligned on the top of the toast container, not centered inside as it should:

enter image description here

Any ideas on what could be wrong?

like image 257
Ricardo Avatar asked Feb 12 '14 23:02

Ricardo


People also ask

How do you change the position of a toast message?

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.

Why is toast not working in Android Studio?

If a toast message is not getting displayed when you run your android Application, 1. Check that you have used . show() method on the toast object as an initial troubleshooting step.


1 Answers

I managed to fix it. The problem lies in applying the attribute android:fitsSystemWindows to the theme of an activity. I found this answer that explains why that should not be done:

The android:fitsSystemWindows attribute is intended for usage on views in layout xml, not in themes.

What you're seeing is the effect of the way the styled attribute system works in Android. If no attribute is specified on the view element or in the explicit style given to the view, the framework checks to see if that attribute has been specified on the theme itself. If it is found there, that value is used. Since the views used by toasts use your activity's theme, the default value of false is overridden and you see this behavior.

You're not just changing the fitsSystemWindows default for your top-level views by specifying it in the theme, you're overriding it for all views with that theme, which isn't what you want. You should only specify fitsSystemWindows on views within your layouts or in styles that you explicitly apply to views within your layouts, not on themes.

Just apply the attribute to the topmost ViewGroup of the activity (or style it) instead of its theme and the toast will be formatted correctly.

like image 159
Ricardo Avatar answered Oct 10 '22 05:10

Ricardo