RelativeLayout 中的 WebView 不居中

WebView in RelativeLayout doesn't center

我有一个布局:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <WebView
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

查看 Android Studio 布局设计器时,WebView 按预期居中。当推送到设备或模拟器中的 运行 时,WebView 左对齐,忽略 centerHorizontal 标签。下面是启用显示视图边界的屏幕截图。

如何让 WebView 居中?

确保父级设置为 match_parent 这样。

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true" />
       </RelativeLayout>

   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

试试这个

<WebView
    android:layout_width="400dp"
    android:layout_height="match_parent"
    android:layout_centerInParent="true" />

如果你想让一个视图居中对齐,你可以在父视图上使用 android:centre view.It 就可以了。 因此,代码将更改为

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:gravity="centre">
    <WebView
        android:layout_width="400dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

希望对您有所帮助:)