Android 不同View ID相同
来源:互联网 发布:java毫秒转换成时分秒 编辑:程序博客网 时间:2024/04/28 06:41
今天在写一段代码是,两个Activity的Button设置了相同的ID,竟然没有报错。然后查看R.java文件,发现class id中也只生成了一个Button变量,且分别在两个Activity中进行访问时均可达到预期效果,觉得奇怪。
一,查阅google帮助文档,现引用如下:
地址:http://developer.android.com/reference/android/view/View.html
IDs
Views may have an integer id associated with them. These ids are typically assigned in the layout XML files, and are used to find specific views within the view tree. A common pattern is to:- Define a Button in the layout file and assign it a unique ID.
<Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text"/>
- From the onCreate method of an Activity, find the Button
Button myButton = (Button) findViewById(R.id.my_button);
View IDs need not be unique throughout the tree, but it is good practice to ensure that they are at least unique within the part of the tree you are searching.
想必大家应该明白一些了吧。
二,再借鉴网友的理解,记录如下:
地址:http://www.hackvip.com/mobiwen/html/Mobile_252534.html
1.实验:通过布局编辑器强行指定两个button id相同,然后在代码中通过findViewById()获得句柄后修改其文本。
实验结果:只有一个button的文本变化了,另一个不受影响。
2.实验:主布局只放一个linearLayout,代码中动态的new 一个button,然后同过Layout.addView()多次重复添加。
实验结果:发现程序直接报错不让运行了。
3.实验:主布局放置两个linearLayout,代码中new一个button后,通过Layout.addView()分别添加到两个不同布局中去。
实验结果:发现程序直接报错不运行了。
4.实验:Activity主布局放置一个按钮Id为btn001,创建一个对话框,其布局中也放置一个按钮,id同样为btn001,在Activity以及Dialog的
onCreate函数中都通过findViewById来查找btn后修改文本。
实验结果:两个按钮的文本都修改成了各自的文本,互不影响。
5.实验:Activity中通过new创建一个button;将新创建的button添加到Activity上;创建一个对话框,将这个button再添加到对话框上。
实验结果:程序运行出错。
结论:
1.同一工程中的View的ID可以一样,在R文件中,同样的ID只会生成一个数据项。
2.两个同ID的View被同一个View显示时,通过findViewById只能访问其中一个。
3.同一个View(即new出来的句柄)只能被一个View管理,不能多次添加到另一个View或者另外多个View,否则程序运行出错。
- Android 不同View ID相同
- View不同,id相同的问题
- [转]Android试验:如果View的ID相同会出现什么效果?
- id相同名称不同多条数据,名字进行累加
- CMFCMenuBar和CMFCToolBar相同ID,在显示不同标签文字
- 获取相同name 不同id 的input控件
- android 不相同分辨率不同尺寸和相同分辨率不同尺寸自适应屏幕解决方法
- Android 数据恢复 view的id
- 关于Android开发中的view的id
- Android 动态设置view的id,id设置为数字
- android 在不同的 xml 中的 id 可以不同
- android robotium获取相同id的的控件
- android robotium获取相同id的的控件
- android robotium获取相同id的的控件
- android robotium获取相同id的的控件
- SQL删除id号不同,其他都相同的学生冗余信息
- 用SQL语句删除除了id不同,其他都相同的学生表信息
- 用Jquery怎么删除class相同 但id不同的元素?
- C++程序设计语言--第六章:表达式和语句
- JDK里面的hash算法
- Java开发三剑客JSF2.0、EJB3.1、JPA2.0现状及发展
- session
- struts2 单个文件上传的三种方法以及多文件上传
- Android 不同View ID相同
- tgggggggggg
- 【堆】B-Station
- 圈圈USB开发板 IDE40
- vc2008 fstream不支持中文路径的解决方案
- C++内存管理详解
- Eclipse常用快捷键
- 详解c中指向指针的指针
- C++程序设计语言--第七章:函数