android UI优化 - <include> 标

作者: TryEnough | 来源:发表于2019-01-24 16:34 被阅读9次

    原文链接

    更多教程


    你将学到

    1.<include>标签的用法
    2.<include>标签的使用例子
    3.<include>标签的使用注意

    <include>标签简介

    你一定经常遇到相似度很高的UI需求:比如同一种标题栏、同一个样式的弹窗、按钮...等等。
    每次都重复的写一样的布局代码么?
    答案肯定是:NO !!!
    提高布局的复用性,可以使用<include>标签

    使用<include>标签的例子

    创建重用的布局

    将你想重用的布局代码封装到一个文件中,这里给出一个例子:

    titlebar.xml

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width=”match_parent”
        android:layout_height="wrap_content"    // 注意点 1 将在下面讲解
        android:background="@color/titlebar_bg">
    
        <ImageView android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:src="@drawable/gafricalogo" />
    </FrameLayout>
    

    这里的根结点FrameLayout就是你想添加入的Layout类型

    使用<include>引用

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/app_bg"
        android:gravity="center_horizontal">
    
        <include layout="@layout/titlebar"/>   // 注意点 2 将在下面讲解
    
        <TextView android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:text="@string/hello"
                  android:padding="10dp" />
    
        ...
    
    </LinearLayout>
    

    引入的时候,你是可以重新覆盖源文件的一些android:layout_*属性,但是必须将android:layout_height 和 android:layout_width同时覆盖才会有效。

    注意点

    上文我们有两个预留的注意点,假如在注意点1处给FrameLayout设置了id,也在注意点2处给include设置了id,那么请务必保持两个id相同,否则在你findViewById的时候可能会发生空指针找不到布局文件,原因是布局的id被覆盖掉了。解决办法是:要么两个id相同,要么只设置其中一个有id。

    原文链接

    更多教程

    相关文章

      网友评论

        本文标题:android UI优化 - <include> 标

        本文链接:https://www.haomeiwen.com/subject/ywgyxqtx.html