Display Toast messages at different positions

We can apply Gravity to the toast message to display it at various positions on the screen. Below are codes provided for displaying a Toast message at TOP, BOTTOM, RIGHT, LEFT, CENTER, TOP LEFT, and BOTTOM RIGHT positions.

// Display Toast at TOP
Toast toast1 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP, 0, 0);
toast1.show();

// Display Toast at BOTTOM
Toast toast2 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast2.setGravity(Gravity.BOTTOM, 0, 0);
toast2.show();

// Display Toast on RIGHT side
Toast toast3 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast3.setGravity(Gravity.RIGHT, 0, 0);
toast3.show();

// Display Toast on LEFT side
Toast toast4 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast4.setGravity(Gravity.LEFT, 0, 0);
toast4.show();

// Display Toast in CENTER
Toast toast5 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast5.setGravity(Gravity.CENTER, 0, 0);
toast5.show();

// Display Toast on TOP LEFT
Toast toast6 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast6.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast6.show();

// Display Toast at BOTTOM RIGHT
Toast toast7 = Toast.makeText(MainActivity.this, "This is my toast message.", Toast.LENGTH_SHORT);
toast7.setGravity(Gravity.BOTTOM|Gravity.RIGHT, 0, 0);
toast7.show();

The method used for displaying Toast at different positions is .setGravity(int gravity, int xOffset, int yOffset).

Leave a Reply