Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text in a Toast

I was wondering if there was a way to display all text in a Toast to be centered. For instance, I have a Toast that has 2 lines of text in it. For purely aesthetic reasons, I would like the text to center-aligned instead of left-aligned. I've looked through the documentation and can't find anything about it. Is there a simple way to do this that I have missed?

like image 482
Sonoman Avatar asked Aug 19 '10 13:08

Sonoman


People also ask

How do you center a toast message?

A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.

How do I make my text centered?

Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center. In the Apply to box, click Selected text, and then click OK.

What is a toast message give example?

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.

What are the main 3 parameters taken by a method when displaying a toast message and what it returns respectively?

This method takes three parameters: the application Context, the text message, and the duration for the toast. You can configure the position of a Toast. A standard toast notification appears near the bottom of the screen, centered horizontally.


2 Answers

Adapted from another answer:

Toast toast = Toast.makeText(this, "Centered\nmessage", Toast.LENGTH_SHORT); TextView v = (TextView) toast.getView().findViewById(android.R.id.message); if( v != null) v.setGravity(Gravity.CENTER); toast.show(); 
like image 92
Marc Avatar answered Oct 25 '22 15:10

Marc


Toast is built on a TextView and the default gravity of it is left aligned. So, you need to create your own TextView like this for instance :

<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); 
like image 37
Sephy Avatar answered Oct 25 '22 15:10

Sephy