Android开发疑难杂症之include布局文件
2015-12-25 17:10
260 查看
前言
有个需求是在不同的布局文件中引入相同的一个顶部toolbar的布局文件,因此用到include。我的toolbar文件是这样的称之为layout_toolbar。
***xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:popupTheme="@style/ThemeOverlay.AppCompat.Light" android:theme="@style/AppTheme" app:theme="@style/ThemeOverlay.AppCompat.ActionBar"></android.support.v7.widget.Toolbar>
主布局文件的结构是一个RelativeLayout,其内部上面引入toolbar,toolbar下面是一个scrollView。
奇怪现象
<include layout="@layout/include_toolbar"/> <ScrollView android:layout_below="@id/toolbar" 。。。
这里有个奇怪现象,直接这样预览都无法预览,scrollView中无法通过id应用include的控件的。参考之前的一个一个项目(称之为A,现在出问题的这个项目称之为B),layout_below=”@id/toolbar”变成
layout_below=”@+id/toolbar”,加上了个加号,从原理上来说,这是不应该的,而且从运行结果来看也不对。但是参考的那个项目用了加号,成功编译运行。仔细检查,发现可能是这两个项目之间的依赖注入模块不同(因为Butterknife的注入运行时报错,找不到toolbar)。把B项目依赖注入从ButterKnife换成XUtil中自带的依赖注入。一切ok。
但是我这样的强迫症患者不能就此罢休。
ScrollView android:layout_below=”@id/toolbar”不能加上加号就是不能,不能因为暂且有结果了,就加上了。
分析
两条结论之前的需求应该是在scrollView设置below include之下。我们可以给include一个id,作为scrollView的参考
1. include和其它组件标签(RelativeLayout、LinearLayout、TextView等)一样,都可以使用layout属性来设置布局文件的宽高和位置
鉴于此,有人将其看作一个类似于LinerLayout的布局,个人感觉是不正确的,include应该只是表示插入,拼接。
但需要注意的是:必须要复写android:layout_width和android:layout_height属性才能使用其它属性(比如:android:layout_grivity、android:layout_align…、android:id等),这样可以避免include引用layout中的子组件属性影响到include的布局效果。
2. include添加配置属性,因为重写了根布局的属性,b文件(主文件)下的根布局的layout就不起作用了。不仅仅如果include指定了id的话,就不能直接把它里面的控件当成主xml中的控件来直接获得了,必须先获得这个xml布局文件,再通过布局文件findViewById来获得其子控件。当没有指定id的时候,只能直接this. findViewById来获得其子控件。至于原因,我们还是归因于对include下的布局文件的调用机制。(亲测)
结论
我们在程序中需要直接通过id查找include布局文件中的组件,因此我们不能通过给include id让scrollView参考的方式。我们将整个include的布局在scrollView之上等效为,scrollView在include布局中的一个组件之下。
直接使用layout_below=”@id/toolbar”(上面说的“一个组件”),这种会出现
上面提到那个项目使用@+id/toolbar,ok。应该是因为我们这里include中只有一个组件toolbar。就将@+id后面的名字给了include中的toolbar。
最佳实践
在布局中使用include时候,在include中使用LInerLayout类似的布局嵌套一层,不要在include设置各种属性,极容易出各种问题。参考文章
http://www.tqcto.com/article/mobile/79638.htmlhttp://zmywly8866.github.io/2015/02/01/android-include-tag-use-tips.html
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories