转自: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,否则程序运行出错。

最新文章

  1. javascript判断数组中是否包含某个元素
  2. python利用redis构成一个队列
  3. windbg学习----.process
  4. HDU2191悼念512汶川大地震遇难同胞——珍惜现在,感恩生活[多重背包]
  5. dp --- Codeforces 245H :Queries for Number of Palindromes
  6. Laravel教程 三:视图变量传递和Blade
  7. Visual Studio Online Integrations-Customer support
  8. 又一个提示框思密达,腾讯UED
  9. VIM实用基本操作技巧
  10. POJ 3259 Wormholes (最短路)
  11. 关于Get和Post的学习笔记(五)
  12. PyQt写的浏览单web页面的browser - 开源中国社区
  13. JavaScript获取浏览器信息的方法
  14. Codeforces 438D The Child and Sequence
  15. 初学Python3 - 写一个登录程序
  16. [Android FrameWork 6.0源码学习] View的重绘过程之WindowManager的addView方法
  17. redis和spring集成
  18. ppt复制文本框文字到word的方法
  19. [Java in NetBeans] Lesson 04. Class / Objects
  20. restful 涵义

热门文章

  1. 洛谷——P2388 阶乘之乘
  2. Nginx反代,后端一个IP绑定多个SSL证书,导致连接失败之解决方法:HTTPS和SNI扩展
  3. 【构造】【贪心】hdu6090 Rikka with Graph
  4. 【KMP求最小周期】POJ2406-Power Strings
  5. [NOIp2017提高组]宝藏
  6. Java高级架构师(一)第34节:Nginx的Http模块部分的指令
  7. 移动应用安全开发指南(Android)--数据传输
  8. golang slice 切片原理
  9. C# 获取文件版本
  10. node.js+mysql增删查改