Android布局优化之include标签详解

一、include标签(布局重用)
1、说明:该标签的目的是解决重复定义布局的问题而诞生的,提高代码的复用

2、使用方法:

    <include android:id="@+id/my_title_ly" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        layout="@layout/my_title_layout" />
my_title_layout.xml
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" android:id="@+id/my_title_parent_id" 
    android:layout_height="wrap_content" > 
    <ImageButton android:id="@+id/back_btn" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:src="@mipmap/ic_launcher" /> 
    <TextView android:id="@+id/title_tv" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_centerVertical="true" 
        android:layout_marginLeft="20dp" 
        android:layout_toRightOf="@+id/back_btn" 
        android:gravity="center" 
        android:text="我的title" 
        android:textSize="18sp" /> 
</RelativeLayout>

include布局文件:

<?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" > 
    <include android:id="@+id/my_title_ly" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        layout="@layout/my_title_layout" /> 
</LinearLayout>

4、注意事项:
子控件抛出空指针
的情况
include标签若指定了ID属性,而你的layout也定义了ID,则你的layout的ID会被覆盖。如果findViewById()查找layout的Id来查找子控件,会出现这种情况。
解决:不用上边的方法。可以直接查找子控件的id。或者查找include标签的id来查找子控件。


猜你喜欢

转载自blog.csdn.net/weimeig/article/details/80238468