当前位置: 代码迷 >> Android >> Android格局技巧:巧用merge,简化布局层次
  详细解决方案

Android格局技巧:巧用merge,简化布局层次

热度:70   发布时间:2016-05-01 15:48:53.0
Android布局技巧:巧用merge,简化布局层次

1、首先我要说的是每一Android UI的根部结构是下面的样子:整个窗体是线性布局,下面是两个FrameLayout,分别是TitleFrame和ContentFrame,我们所要做的工作就是在ContentFrame下面布局我们自己的UI。

2、假如你的UI根布局是FrameLayout,例如下面:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
? ?
android:layout_width="fill_parent"
? ?
android:layout_height="fill_parent">

? ?
<ImageView ?
? ? ? ?
android:layout_width="fill_parent"
? ? ? ?
android:layout_height="fill_parent"
? ?
? ? ? ?
android:scaleType="center"
? ? ? ?
android:src="@drawable/golden_gate" />
? ?
? ?
<TextView
? ? ? ?
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" />

</FrameLayout>

?那你的FrameLayout就是多余的了,既然你在FrameLayout中使用了“fillparent”,那么无论你如何设置 background, extra padding 或者a gravity都没有作用,因为他和ContentFrame的大小一样。既然这个FrameLayout是多余的,为什么我们不去掉他呢?这时我们可以使用<merge>代替FrameLayout,因为当LayoutInflater 遇见FrameLayout,就会跳过它,用他的子标签代替他,就想下面的布局:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

? ?
<ImageView ?
? ? ? ?
android:layout_width="fill_parent"
? ? ? ?
android:layout_height="fill_parent"
? ?
? ? ? ?
android:scaleType="center"
? ? ? ?
android:src="@drawable/golden_gate" />
? ?
? ?
<TextView
? ? ? ?
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" />

</merge>

对应的Layout Level如下图:

如果你的Xml文件的根标签不是FrameLayout那就不能用这种方法了。不过我们可以使用<include>标签,让我们的层次结构变得清晰明了。

?

1 楼 烧伤的火柴 2011-11-28  
太牛了  刚好用到这块知识
  相关解决方案