Android在layout xml中使用include[转]

简介:

在Android的layout样式定义中,可以使用xml文件方便的实现,有时候为了模块的复用,使用include标签可以达到此目的。例如:

<include layout="@layout/otherlayout"></div> 

Android开发的官方网站的说明在这里
其中,有提到:

Similarly, you can override all the layout parameters. This means that any android:layout_* attribute can be used with the <include> tag.

意思是任何android:layout_*属性都可以应用在标签中。

如果使用如下代码:

<Relativelayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" > <Textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/somestring" android:id="@+id/top" /> <include layout="@layout/otherlayout" android:layout_below="@id/top" /> </Relativelayout > 

发现include的otherlayout,并没有在如我们预期的在id/top这个TextView下面,而是忽略了android:layout_below属性。经过Google发现,很多人遇到类似的问题。

有解决方法是在include的外面再包一层LinearLayout,如下:

<Linearlayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_below="@id/top" > <include layout="@layout/otherlayout"> </Linearlayout > 

在Statckoverflow上找到了更好的解决方法:
解答道:必须同时重载layout_width和layoutheight熟悉,其他的layout*属性才会起作用,否这都会被忽略掉。上面的例子应该写成这样:

<include layout="@layout/otherlayout">
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_below="@id/top" /> 

另外,关于xml的复用,还可以使用merge标签,merge标签主要是用来优化显示的,减少View树的层级,可以参考这里:https://developer.android.com/resources/articles/layout-tricks-merge.html 翻译版在这里:http://apps.hi.baidu.com/share/detail/20871363

 

from:http://www.race604.com/using-include-in-layout/

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!




















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/p/4819049.html ,如需转载请自行联系原作者
相关文章
|
7月前
|
API Android开发
Android 自定义最大宽度,高度, 宽高比例 Layout
Android 自定义最大宽度,高度, 宽高比例 Layout
|
6月前
|
开发工具 Android开发
Android Studio layout 文件没有代码提示
Android Studio layout 文件没有代码提示
164 0
|
8月前
|
XML Java Android开发
#4,Android Studio Android程序结构 工程目录介绍 文件作用 运行配置文件AndroidManifest.xml
#4,Android Studio Android程序结构 工程目录介绍 文件作用 运行配置文件AndroidManifest.xml
|
8月前
|
Android开发
Android 使用DataBinding时 将布局页面转换为数据绑定布局(Convert to data binding layout) 不出现提示解决办法
Android 使用DataBinding时 将布局页面转换为数据绑定布局(Convert to data binding layout) 不出现提示解决办法
90 0
|
8月前
|
Android开发
Android 获取include标签中的控件属性并设置事件
Android 获取include标签中的控件属性并设置事件
138 0
|
8月前
|
XML Android开发 数据格式
Android Binary XML file line #50: Error inflating class androidx.cardview.widget.CardView 错误
Android Binary XML file line #50: Error inflating class androidx.cardview.widget.CardView 错误
51 0
|
8月前
|
XML 应用服务中间件 Android开发
Android的XML文件解析之PULL解析
Android的XML文件解析之PULL解析
|
8月前
|
XML Android开发 数据格式
Android XML 布局基础(八)帧布局 - GridLayout
Android XML 布局基础(八)帧布局 - GridLayout
90 0
|
8月前
|
XML Android开发 数据格式
Android XML 布局基础(七)帧布局 - FrameLayout
Android XML 布局基础(七)帧布局 - FrameLayout
54 0
|
8天前
|
XML Java 数据库连接
mybatis中在xml文件中通用查询结果列如何使用
mybatis中在xml文件中通用查询结果列如何使用
9 0