Android 不同View ID相同
转自:http://blog.csdn.net/program035/article/details/6905045
今天在写一段代码是,两个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,否则程序运行出错。
最新文章
- javascript判断数组中是否包含某个元素
- python利用redis构成一个队列
- windbg学习----.process
- HDU2191悼念512汶川大地震遇难同胞——珍惜现在,感恩生活[多重背包]
- dp --- Codeforces 245H :Queries for Number of Palindromes
- Laravel教程 三:视图变量传递和Blade
- Visual Studio Online Integrations-Customer support
- 又一个提示框思密达,腾讯UED
- VIM实用基本操作技巧
- POJ 3259 Wormholes (最短路)
- 关于Get和Post的学习笔记(五)
- PyQt写的浏览单web页面的browser - 开源中国社区
- JavaScript获取浏览器信息的方法
- Codeforces 438D The Child and Sequence
- 初学Python3 - 写一个登录程序
- [Android FrameWork 6.0源码学习] View的重绘过程之WindowManager的addView方法
- redis和spring集成
- ppt复制文本框文字到word的方法
- [Java in NetBeans] Lesson 04. Class / Objects
- restful 涵义