LinearLayout 可以嵌套使用,当一个LinearLayout作为其它Layout子类时,可以使用android:baselineAlignedChildIndex 指定该LinearLayout的哪个子类需要和其它支持baseline的UI控件对齐。
android:baselineAlignedChildIndex 值必须为整数,为子View的序号(从0开始)。
本例 和下面几个 Nested Example ,Google提供的示例是不正确的,根本就没有能够演示android:baselineAlignedChildIndex 的用法. 这是因为LinearLayout 使用了center_vertical的对齐方式,此时baseline 对齐就不起作用了。参见Android ApiDemos示例解析(135):Views->Layouts->Baseline->3. Center。
修改baseline_nested_1.xml 去掉所有的android:layout_gravity=”center_vertical” ,修改后的XML如下:
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”horizontal”
android:gravity=”center_horizontal“
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginRight=”3dip”
android:layout_gravity=”center_vertical”
android:text=”@string/baseline_nested_1_label” />
<!– We want the middle textview of this vertical linear layout to
be baseline aligned with the others.–>
<LinearLayout
android:orientation=”vertical”
android:baselineAlignedChildIndex=”1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center_vertical”>
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/arrow_up_float”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginRight=”5dip”
android:text=”@string/baseline_nested_1_label” />
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/arrow_down_float”/>
< /LinearLayout>
<!– We want the third index textview of this vertical linear layout to
be baseline aligned with the others.–>
<LinearLayout
android:orientation=”vertical”
android:baselineAlignedChildIndex=”2″
android:layout_width=”wrap_content”
android:layout_gravity=”center_vertical”
android:layout_height=”wrap_content”>
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/arrow_up_float”/>
<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/arrow_up_float”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginRight=”5dip”
android:text=”@string/baseline_nested_1_label” />
< /LinearLayout>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textSize=”20sp”
android:layout_gravity=”center_vertical”
android:text=”@string/baseline_nested_1_label” />
</LinearLayout>
本例嵌套了两个子LinearLayout ,第一个将android:baselineAlignedChildIndex 设为1,第二个将android:baselineAlignedChildIndex 设为2 ,都将子LinearLayout 中的TextView和其它支持baseline对齐的UI(如TextView) 实现文字baseline 对齐。