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?


Solution 1:

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

Solution 2:

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

Solution 3:

Without the hacks:

String text = "Some text";
Spannable centeredText = new SpannableString(text);
centeredText.setSpan(
    new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER),
    0, text.length() - 1,
    Spannable.SPAN_INCLUSIVE_INCLUSIVE
);

Toast.makeText(getActivity(), centeredText, Toast.LENGTH_LONG).show();

There are also another alignments besides center.

cf. Multiple alignment in TextView?

Solution 4:

It is dirty hack, but

((TextView)((LinearLayout)toast.getView()).getChildAt(0))
    .setGravity(Gravity.CENTER_HORIZONTAL);