Android布局在Pixel、Nexus等谷歌系列手机上显示异常问题求助
问题根因
该问题本质是不同厂商ROM对CoordinatorLayout的兜底布局逻辑存在定制差异,谷歌Pixel系列搭载的原生AOSP系统严格遵循CoordinatorLayout的官方布局规则,而其他厂商修改了默认兜底逻辑,所以仅在谷歌手机上出现布局异常,具体触发点是你直接放在CoordinatorLayout下的TextView没有指定明确的布局定位属性。
解决方案
按优先级尝试以下操作即可修复:
- 给所有直接放在CoordinatorLayout下的子View添加明确的
android:layout_gravity属性,指定View的位置,比如要让TextView居中显示就添加android:layout_gravity="center",要放在顶部居中就加android:layout_gravity="top|center_horizontal"。 - 给CoordinatorLayout明确设置
android:fitsSystemWindows="false",避免原生系统默认的WindowInsets处理导致布局偏移,如果你需要适配状态栏沉浸式,再单独给需要偏移的子View加Insets适配逻辑即可。 - 升级CoordinatorLayout依赖到最新稳定版,避免旧版本库本身的布局计算bug:
implementation "androidx.coordinatorlayout:coordinatorlayout:1.2.0"
修改后的XML代码示例
<androidx.coordinatorlayout.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="false" app:touchListener="@{0L}"> . . . <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Some Text" android:background="@color/color_primary"/> </androidx.coordinatorlayout.widget.CoordinatorLayout>
异常效果参考

内容的提问来源于stack exchange,提问作者Mohammad Elsayed
相关产品推荐
相关产品推荐

