Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

This situation occurs because in the horizontal screen state, the width of the navigation bar will also be calculated, regardless of whether the navigation bar is hidden or not, so you can subtract half the width of the navigation bar.

toast.setGravity(Gravity.CENTER, getNavigationBarHeight() / 2, 0); 

    private int getNavigationBarHeight() {
        Resources resources = this.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return resources.getDimensionPixelSize(resourceId);
        }
        return 0;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top