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


原创粉丝点击