在 Android 開發中,使用 RelativeLayout 布局時,若將 WebView 設置為 match_parent,底部的 RadioGroup(包含圖片按鈕)往往會被 WebView 遮擋,導致無法顯示。開發者嘗試調整 WebView 大小均無效,WebView 始終全屏顯示網頁內容。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/zhaopin"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<RadioGroup
android:id="@+id/main_fragment_rgp"
android:layout_width="match_parent"
android:layout_height="46dp"
android:layout_alignParentBottom="true"
android:layout_weight="0.04"
android:background="@drawable/shape_bottom_radio_group_back"
android:checkedButton="@+id/main_rbn_news"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/main_rbn_news"
android:layout_width="71dp"
android:layout_height="match_parent"
android:button="@null"
android:drawableTop="@drawable/selector_rbn_news"
android:onClick="news" />
<RadioButton
android:id="@+id/main_rbn_youhui"
android:layout_width="92dp"
android:layout_height="match_parent"
android:button="@null"
android:drawableTop="@drawable/selector_rbn_postbar"
android:onClick="youhui" />
<RadioButton
android:id="@+id/main_rbn_zhaopin"
android:layout_width="82dp"
android:layout_height="match_parent"
android:button="@null"
android:drawableTop="@drawable/zhaopin"
android:onClick="zhaopin" />
<RadioButton
android:id="@+id/main_rbn_about"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:button="@null"
android:drawableTop="@drawable/about"
android:onClick="about" />
</RadioGroup>
</RelativeLayout>
關鍵在於正確使用 layout_weight 與 layout_height="0dp" 結合。將 WebView 的高度設置為 0dp,並賦予權重 1,使其佔據剩餘空間;底部 RadioGroup 固定高度(如 46dp),不設置權重或權重為 0。同時確保 RadioGroup 使用 android:layout_alignParentBottom="true" 固定在底部。
android:layout_height="0dp" 和 android:layout_weight="1"android:layout_height="46dp"、android:layout_alignParentBottom="true"、android:layout_weight="0"(或不寫)RelativeLayout 不支持 weight 屬性,上述代碼實際上混用了 LinearLayout 的屬性。正確做法是改用 LinearLayout(垂直方向),或在 RelativeLayout 中通過 layout_above 將 WebView 置於 RadioGroup 之上。推薦使用 LinearLayout 並配合 weight 實現自適應布局。
LinearLayout,android:orientation="vertical"。layout_height="0dp"、layout_weight="1"。這樣即可實現 WebView 自適應填充內容區域,底部導航欄始終可見的效果。