黑马程序员技术交流社区
标题: [深圳特色][问答网]Layout文件中id和+id的用法 [打印本页]
作者: 深圳黑马程序员 时间: 2015-12-6 20:17
标题: [深圳特色][问答网]Layout文件中id和+id的用法
本帖最后由 xiaoqing 于 2015-12-6 20:26 编辑
在平常开发用,经常会用到layout文件来编写界面,但是有时候会报找不到id的错误,这是什么原因造成的呢?下面深圳的老师来回答一下问题。
学生问题:+id问题,有时候用+id,有时候用id,到底怎么使用?老师回答:
很多人使用id的时候,以为只要是前面用id,那么它相对的布局都不要用加号。
- <TextView
- android:id="@+id/tv"
- android:layout_above="@id/aa"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
- <TextView
- android:id="@+id/aa"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
- <TextView
- android:id="@+id/bb"
- android:layout_above="@id/aa"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
复制代码
这种是对知识的误读。
在程序读取xml的时候是顺序读取的。所以正确的原则应该是这样的。
下面的组件:如果用的是above,而你的above对象是在这个组件的下面(代码位置)。
那么此时用+id,如果是出现在他的前面,那么above属性里面面应该是用id(不用加号)
正确的代码是这样的:
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
-
- <TextView
- android:id="@+id/tv"
- android:layout_above="@+id/aa"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
- <TextView
- android:id="@+id/aa"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
- <TextView
- android:id="@+id/bb"
- android:layout_above="@id/aa"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
-
-
-
- </RelativeLayout>
复制代码+id的正确意思是“如果没有这个id,则创建”意思。在平时开发中,要注意这个差别。
深圳校区除了全国独有问答网,就业老师面试服务,还有更多神秘惊喜等着你,咨询热线:0755-66689855
作者: 小欢 时间: 2015-12-6 22:37
@+id是创建view的id,@id是引用此id的view
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |