前端之家收集整理的这篇文章主要介绍了
xml--include用法--xml文件模块化,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Android在xml文件中可使用include包含其他定义好的布局, 可以将多处用到的布局单独出来,然后用include包含进来,这种包含方法相当于把原来布局的一部分代码独立出来,供大家共同使用,也就相当于面向对向中的类的概念差不多。下面我们逐步讲解include的作用。
先看下我们要实现的整体界面:
一、未使用Include时
通常情况下,我们直接就能写出布局代码,下面是所使用的XML代码:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical">
- <!--第一部分-->
- TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="#ff0000"
- android:text="第一个BTN"/>
- Button
- android:id="@+id/mybutton"
- android:text="OneButton"
- <!--第二部分-->
- android:background="#00ff00"
- android:text="第二个BTN"
- android:id="@+id/mybutton"
- android:layout_height="wrap_content"
- android:text="SecondButton" <!--最后的按钮-->
- android:id="@+id/another"
- android:layout_width="wrap_content"
- android:text="AnotherButton"</LinearLayout>
这段代码理解起来一点难度没有,就是几个TextView和几个Button,下面我们用include把这段代码给分割成几个文件,并完成相同的效果;
1、先将上面代码标记有“第一部分”的,代码段分离成一个文件(sublayout1.xml);
@H_
301_355@
android:background="#505050"
android:orientation="vertical" android:background="#ff0000"
android:text="第一个BTN" android:text="OneButton">
2、再将标记有“第二部分”的代码段,分离成第二个文件(sublayout2.xml):
@H_
301_355@
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">