Search code examples
androidtoasttext-alignmentandroid-toast

How to Align Android Toast as Centered


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();

Solution

  • 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