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. ?<Buttonandroid: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,否則程序運行出錯。
轉載于:https://www.cnblogs.com/zl1991/p/5123519.html
總結
以上是生活随笔為你收集整理的Android 不同View ID相同的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么沙拉酱热量最低?
- 下一篇: 鸡肉还能怎么做?