Android中使用include标签和merge标签重复使用布局

2019-12-10 20:02:04丽君

 
    <TextView android:layout_width=”match_parent”
              android:layout_height="wrap_content"
              android:text="@string/hello"
              android:padding="10dp" />
 
    ...
 
</LinearLayout>

 

你同样可以覆盖所有的布局参数(android:layout_*属性)

复制代码
<include android:id=”@+id/news_title”
         android:layout_width=”match_parent”
         android:layout_height=”match_parent”
         layout=”@layout/title”/>

 

可是,如果你要用include标签覆盖布局属性,为了让其他属性生效,就必须覆盖android:layout_height和android:layout_width。

使用<merge/>标签

<merge/>标签帮助你排除把一个布局插入到另一个布局时产生的多余的View Group.如,你的被复用布局是一个垂直的线性布局,包含两个子视图,当它作为一个被复用的元素被插入到另一个垂直的线性布局时,结果就是一个垂直的LinearLayout里包含一个垂直的LinearLayout。这个嵌套的布局并没有实际意义,而且会让UI性能变差。

为了避免插入类似冗余的View Group,你可以使用<merge/>标签标签作为可复用布局的根节点,如:

复制代码
<merge xmlns:android="http://www.easck.com/apk/res/android">
 
    <Button
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="@string/add"/>
 
    <Button
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="@string/delete"/>
 
</merge>