Android开发Toast消息无法居中显示 如何配置实现屏幕居中展示?
问题原因
从Android 11(API level 30)开始,系统对原生文本Toast做了强制限制:Toast.setGravity()方法被正式废弃,所有前台应用弹出的纯文本Toast的位置会被系统强制锁定在底部默认位置,自定义gravity参数会被直接忽略。
除此之外,部分厂商定制ROM(如MIUI、HarmonyOS等)也会在低版本系统中修改Toast的渲染逻辑,即便是API 30以下的设备也可能出现自定义位置不生效的情况。
可行解决方案
方案1:使用自定义View的Toast(全版本兼容,推荐)
自定义View的Toast不受系统文本Toast的位置限制,所有Android版本都可以正常设置位置:
- 先在
res/layout目录下创建自定义Toast布局文件custom_toast.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_container" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/toast_background" android:paddingHorizontal="16dp" android:paddingVertical="12dp" android:orientation="horizontal"> <TextView android:id="@+id/toast_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FFFFFF" android:textSize="14sp"/> </LinearLayout>
- 调用代码示例:
// 加载自定义布局 LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.custom_toast, findViewById(R.id.toast_container)); TextView text = layout.findViewById(R.id.toast_text); text.setText("Please Set a Profile"); // 配置Toast Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.setGravity(Gravity.CENTER, 0, 0); // 直接设置居中,正常生效 toast.show();
方案2:适配API 30以下设备的原生文本Toast
如果不需要兼容Android 11及以上版本,你原有代码只需要调整gravity参数为同时包含水平+垂直居中的flag即可:
// 仅API < 30生效 Toast toast = Toast.makeText(this,"Please Set a Profile", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); // Gravity.CENTER = 垂直+水平居中 toast.show();
方案3:替换为官方推荐的提示组件
如果你不需要严格使用Toast,Google官方更推荐使用Snackbar或者DialogFragment实现自定义位置的消息提示,不会受系统版本和厂商定制的限制。
内容的提问来源于stack exchange,提问作者Paul Campbell
相关产品推荐
相关产品推荐

