1

How to Align Android Toast as Centered

I saw many related questions in StackOverflow and All over the Internet, but they align the toast centered to the display. But, I want to display the text-centered to my toast!


Example Image

My Code to display my Toast

   timeout_on = Toast.makeText(getBaseContext(), "Screen Timeout is Enabled (Your screen will doesn't sleep from now!)", Toast.LENGTH_SHORT);
   timeout_on.show();
Sam Joshua
  • 310
  • 6
  • 17

3 Answers3

4

Try the following:

Toast timeout_on = Toast.makeText(getBaseContext(), "Screen Timeout is Enabled (Your screen will doesn't sleep from now!)", Toast.LENGTH_SHORT);
TextView v = (TextView) timeout_on.getView().findViewById(android.R.id.message);
if( v != null) v.setGravity(Gravity.CENTER);
timeout_on.show();

This code gets the instance of the TextView inside of your Toast and gives you more room for customization (like setting your text's gravity/alignment).

Answer adopted from Marc's Answer

1

kotlin:

val toast = Toast.makeText(context, "Test", Toast.LENGTH_LONG)
toast.setGravity(Gravity.CENTER, 0, 0)
toast.show()

java:

Toast toast = Toast.makeText(context, "Test", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Hassan
  • 380
  • 6
  • 20
0

Toast is built on a TextView and as you can see by default is left aligned. Create your own text view with the alignment you want and set it to your Toast view

<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:gravity="center_vertical|center_horizontal"
    android:text="all the text you want"
/>

And you assign the TextView to the Toast like this :

Toast t = new Toast(yourContext);
t.setView(yourNewTextView);
DevWithZachary
  • 3,545
  • 11
  • 49
  • 101