加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml--include用法--xml文件模块化

发布时间:2020-12-16 08:28:25 所属栏目:百科 来源:网络整理
导读:Android在xml文件中可使用include包含其他定义好的布局, 可以将多处用到的布局单独出来,然后用include包含进来,这种包含方法相当于把原来布局的一部分代码独立出来,供大家共同使用,也就相当于面向对向中的类的概念差不多。下面我们逐步讲解include的作

Android在xml文件中可使用include包含其他定义好的布局, 可以将多处用到的布局单独出来,然后用include包含进来,这种包含方法相当于把原来布局的一部分代码独立出来,供大家共同使用,也就相当于面向对向中的类的概念差不多。下面我们逐步讲解include的作用。

先看下我们要实现的整体界面:

一、未使用Include时

通常情况下,我们直接就能写出布局代码,下面是所使用的XML代码:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical">
  6. <!--第一部分-->
  7. TextView
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:background="#ff0000"
  11. android:text="第一个BTN"/>
  12. Button
  13. android:id="@+id/mybutton"
  14. android:text="OneButton"
  15. <!--第二部分-->
  16. android:background="#00ff00"
  17. android:text="第二个BTN"
  18. android:id="@+id/mybutton"
  19. android:layout_height="wrap_content"
  20. android:text="SecondButton" <!--最后的按钮-->
  21. android:id="@+id/another"
  22. android:layout_width="wrap_content"
  23. android:text="AnotherButton"</LinearLayout>

这段代码理解起来一点难度没有,就是几个TextView和几个Button,下面我们用include把这段代码给分割成几个文件,并完成相同的效果;

二、使用Include时

1、先将上面代码标记有“第一部分”的,代码段分离成一个文件(sublayout1.xml);

android:background="#505050"
  • android:orientation="vertical" android:background="#ff0000"
  • android:text="第一个BTN" android:text="OneButton">
  • 2、再将标记有“第二部分”的代码段,分离成第二个文件(sublayout2.xml):

    android:background="#00ff00"
  • android:text="第二个BTN" android:text="SecondButton"3、主文件中使用include,将上面两个文件包含进去(activity_main.xml);
    include
  • android:id="@+id/main1"
  • layout="@layout/sublayout1" android:id="@+id/main2"
  • layout="@layout/sublayout2" android:id="@+id/another"
  • android:layout_width="wrap_content"
  • android:text="AnotherButton">

  • 这样就实现了相同的效果,这里可以看到,include并没有其它的功能,只是把一个XML布局引入进来当做自己的布局,跟直接把引用的这段代码写在include处的效果是一样的。

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读