[英]two views with same id
膨脹XML后,android如何使用R.id.id_name
查找視圖?
1.假設我有兩個帶有一個按鈕的XML,每個按鈕具有相同的ID。
2.我誇大了它們並將它們轉換為視圖
3.在R.id類中,兩個按鈕都只會創建一個int
。
android如何使用相同的Resource name(R.id.id_name)區分具有相同id的這些按鈕。
該ID不是唯一參考。
但是,實際上,您可以通過使用父視圖來區分。
如果我們認為“這”是一個活動,請設置包含您的按鈕的布局,然后:
Button button = (Button) this.findViewById( R.id.id_name );
將返回它在布局中找到的第一個(我想-不確定是否定義了實際行為)。
但是,您可能要做的是在某些僅包含一個具有該ID的實例的父視圖上調用findViewById
。
LinearLayout okParent = (LinearLayout) this.findViewById( R.id.okLayout );
LinearLayout cancelParent = (LinearLayout) this.findViewById( R.id.cancelLayout );
Button okButton = (Button) okParent.findViewById( R.id.id_name );
Button cancelButton = (Button) cancelParent.findViewById( R.id.id_name );
從概念上講,這是一種基於路徑的查找。 您應該謹慎設計布局,以使這成為可能。
Android走上了一條輕松之路: ID並不是應用程序范圍內唯一,而是布局范圍內唯一。
R.id.foo
的值在兩個具有foo
id的控件的不同布局中是相同的。 由於他們不競爭唯一性,所以沒關系。
它知道應該使用哪個View
,因為它會在當前設置為內容視圖(或已充氣)的XML文件中查找具有此特定id
View
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.