2014-07-26 41 views
0

說兩款Android GUI對象之間的差異,我們有兩個XML文件,其中這些片段:告訴用相同的ID

firstxml.xml

<?xml version="1.0" encoding="utf-8"?> 
<Button 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/button1 /> 

secondxml.xml

<?xml version="1.0" encoding="utf-8"?> 
<Button 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/button1 /> 

我們onCreate()方法:

//Assume all packages necessary are imported 
public class Example 
{ 
    public void onCreate(Bundle sis) 
    { 
     super.onCreate(sis); 
     setContentView(R.layout.firstxml); 

     Button thisButton = (Button) findViewbyId(R.id.button1); 

    } 
} 

當這段代碼運行時,哪個按鈕被調用並實例化?由於這兩個按鈕位於兩個不同的文件中,因此它將調用firstxml.xml中的按鈕,因爲它是該函數的內容視圖?

在此先感謝您的答案!

回答

1

您正在引用活動的onCreate(Bundle...)方法中的第一個XML佈局文件R.layout.firstxml,因此將在此進行搜索。

任何撥打findViewById(int id);的電話都會在您的虛設佈局R.layout.firstxml中搜索。

當您爲佈局定義/添加新視圖時,會自動生成R.java文件。

您可以多次使用相同的ID,但不在相同的佈局

1

代碼將調用並實例化firstxml.xml文件中設置的button1。

注意對於未來的讀者。如果佈局文件不包含button1,它將拋出空指針異常,編輯器不會知道有錯誤。這是因爲R.id.button1是R.java類中的靜態字段。爲可維護性提供更好的命名約定。

1
Which button is called and instantiated when this code runs? 

由於您使用的firstxml.xml如你撥打的按鈕從XML不是從secondxml.xml按鈕參考活動的佈局。

而在你的R.java中它只會生成該ID的一個實例。

樣本:

public static final class id { 
    public static final int button1=0x7f090009; 
} 

所以當你使用的按鈕,它會首先發現的是參考/檢查佈局的ID,如果它,如果它不存在,那麼它會拋出NPE存在。

2

當您將firstxml設置爲內容視圖時,該佈局會變得膨脹。 findViewById會在當前佈局中查找id,而不是在每個佈局上。

setContentView方法描述回答你的問題。