1.创建可复用的UI组件
我们可以通过使用
内部只允许使用 layout
属性
android:layout_height="fill_parent"
android:layout_width="fill_parent" />
2.与
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
在 HierarchyViewer中查看继承图表,如果仔细观察这张表,我们会发现我们在XML里面定义的FrameLayout 是另外一个FrameLayout 唯一的孩子.
由于使用了fill_parent属性我们的FrameLayout 有与其父节点相同的尺寸,
并且我们没有定义任何的背景, 额外的填充 或gravity属性,因此这个FrameLayout 节点是多余的.这样做会使我们的UI无缘无故的变得复杂起来,怎样才能去掉这个FrameLayout 呢?毕竟XML文件都需要一个根标签和一个表示视图的标签.
LayoutInflater遇到这个标签时,LayoutInflater会跳过这个标签内的内容,然后把这些内容加入到其父节点中去,以上的例子改写如下:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
我们再次查看HierarchyViewer,多余的FrameLayout 节点没有了.
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:okCancelBar="http://schemas.android.com/apk/res/com.example.android.merge">
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:paddingTop="8dip"
android:gravity="center_horizontal"
android:background="#AA000000"
okCancelBar:okLabel="Save"
okCancelBar:cancelLabel="Don't save" />
也可以与
layout="@layout/okcancelbar_button"
android:id="@+id/okcancelbar_ok" />
layout="@layout/okcancelbar_button"
android:id="@+id/okcancelbar_cancel" />
1.它只能作为根标签使用
2.当你inflating一个以
LayoutInflater.from(context).inflate(R.layout.okcancelbar, this, true);