歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 不同View ID相同

Android 不同View ID相同

日期:2017/3/1 11:10:39   编辑:Linux編程

今天在寫一段代碼是,兩個Activity的Button設置了相同的ID,竟然沒有報錯。然後查看R.java文件,發現class id中也只生成了一個Button變量,且分別在兩個Activity中進行訪問時均可達到預期效果,覺得奇怪。

一,查閱google幫助文檔,現引用如下:

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.

想必大家應該明白一些了吧。

二,再借鑒網友的理解,記錄如下:

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,否則程序運行出錯。

Copyright © Linux教程網 All Rights Reserved