Search code examples
androidtoastgravity

Android: Set Toast to the default position (centered, just above the status bar at the bottom)?


I'm having the exact opposite problem of this post - specifically, I want to display a toast in the default location (centered, just above the status bar at the bottom) but it is always appearing horizontally and vertically centered.

Here is the code and call I am using to display the toast (toastNavigation method is in a separate class from call):

public static void toastNavigation(Context context, CharSequence message,
        int duration, int gravity, int gravity_xOffset, int gravity_yOffset) {  
    Toast toast = Toast.makeText(context, message, duration);  
    toast.setGravity(gravity, gravity_xOffset, gravity_yOffset);  
    toast.show();
}

toastNavigation(this, 
    "My message", Toast.LENGTH_SHORT, Gravity.NO_GRAVITY, 0, 0);

Why would my toast be centered even though I am passing in the constant that indicates "...no gravity has been set."? Is there some other constant I should pass to clear GRAVITY constants inherited from the context?


Solution

  • I'm going to assume you have good reason for calling setGravity() at all if you just need the default values.

    The default gravity settings for a Toast are Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, so you can apply those to get the default placement.

    You can see this in the source for Toast...check the initialization of the mGravity field.