Center text in a toast in Android

后端 未结 11 1398
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 01:58

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,

相关标签:
11条回答
  • 2020-12-13 02:04

    It is dirty hack, but

    ((TextView)((LinearLayout)toast.getView()).getChildAt(0))
        .setGravity(Gravity.CENTER_HORIZONTAL);
    
    0 讨论(0)
  • 2020-12-13 02:06

    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);
    
    0 讨论(0)
  • 2020-12-13 02:09

    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.

    source

    0 讨论(0)
  • 2020-12-13 02:16

    Use the Toast's setView(view) function to supply a View with Gravity.CENTER.

    0 讨论(0)
  • 2020-12-13 02:16

    It is work for me:

    Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER| Gravity.BOTTOM, 0, 20);
    toast.show();
    
    0 讨论(0)
  • 2020-12-13 02:16
    Toast t=Toast.makeText(getApplicationContext(),"Text",Toast.LENGTH_LONG);
    t.setText("Password Does't match...");
    t.setGravity(0, 0, 0);
    t.show();
    

    simple code for toast most be center

    0 讨论(0)
提交回复
热议问题