如何将 Android Toast 居中对齐

How to Align Android Toast as Centered

如何对齐 Android Toast 居中

我在 Whosebug 和 All over the Internet 中看到许多相关问题,但它们将 toast 居中对齐到显示。但是,我想在 toast 中显示文本居中!


我用来显示 Toast 的代码

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

Toast 构建在 TextView 上,如您所见,默认情况下是左对齐的。使用您想要的对齐方式创建您自己的文本视图并将其设置为您的 Toast 视图

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

然后像这样将 TextView 分配给 Toast :

Toast t = new Toast(yourContext);
t.setView(yourNewTextView);

科特林:

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

尝试以下操作:

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

此代码获取 Toast 中的 TextView 实例,并为您提供更多自定义空间(例如设置文本的 gravity/alignment).

答案采纳自Marc's Answer