在编写底部导航代码的时候,发现视图中出现大量空白,如下:
布局文件部分为:
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<RadioGroup
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
android:id="@+id/catalog"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:button="@null"
android:id="@+id/btn_simplecal"
android:checked="true"
android:background="@drawable/tab_switcher"
android:drawableTop="@mipmap/simplecal"
android:gravity="center_horizontal|bottom"
android:paddingTop="2dp"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:button="@null"
android:id="@+id/btn_cash_reg"
android:background="@drawable/tab_switcher"
android:drawableTop="@mipmap/cash_reg"
android:gravity="center_horizontal|bottom"
android:paddingTop="2dp"/>
</RadioGroup>
</LinearLayout>
其中只有两个控件,分别fragment和RadioGroup,可以看见,在RadioGroup下面留有大量空白,这种情况是不允许的,然而,该怎样消除呢?
我们可以在API查到,LinearLayout中有一个很重要的属性--android:layout_weight。API是这样描述的:
线性布局支持给个别的子视图设定权重,通过android:layout_weight属性。就一个视图在屏幕上占多大的空间而言,这个属性给其设定了一个重要的值。一个大的权重值,允许它扩大到填充父视图中的任何剩余空间。子视图可以指定一个权重值,然后视图组剩余的其他的空间将会分配给其声明权重的子视图。默认的权重是0.
其中提到,子视图可以指定一个权重值,然后视图组剩余的其他的空间将会分配给其声明权重的子视图。默认的权重是0。也就是说,当在fragment中设置android:layout_weight1,同时,RadioGroup中不设置,则剩余的空白将全部分配给fragment。
到此,底部导航就 顺利完成了。
总结:
layout_weight 就是先按照控件声明的尺寸进行分配,然后剩下的尺寸按weight进行分配。也就是一个控件的尺寸=控件声明的尺寸+(父控件-子控件声明的总尺寸)X(子控件权重/父控件声明的总权重or子控件声明的权重和)
PS:可以在父控件通过weightSum属性设置该父控件内的总权重。