2013-01-08 75 views
0

在我的應用程序中,我打電話setContentView(layout1.xml);,我想要訪問不同佈局文件中的元素,可以將其稱爲layout2.xml。如何參考當前佈局文件以外的佈局文件?

我已經試過

view1 = (View) findViewById(R.layout.layout2); 

,並還增加了一個ID,佈局,並試圖

view1 = (View) findViewById(r.id.layout2); 

無論這些工作。他們編譯得很好,但是當我運行它時,只要我嘗試調用像

button1 = view1.findViewById(R.id.button1); 

我得到一個空指針異常。

+2

需要更多關於你想要完成的細節。 xml文件只定義了'View'的結構,但它僅在被充氣後才通過實例化(通過'setContentView'或'LayoutInflator')實例化。 – iagreen

回答

2

你需要使用一個佈局吹氣,讓您的第二個佈局像這樣:

View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.layout2, null); 

,然後從佈局引用您的按鈕:

Button button1 = view.findViewById(R.id.button1); 
+0

我是否需要安裝特殊軟件包才能獲得'LayoutInflator'?嘗試後,它給了我一個錯誤,當我將鼠標懸停在文本上時,沒有「import ...」選項。 – JuiCe

+0

我是個白癡,我不能拼寫Inflater。 – JuiCe

+0

哈。請注意,還有其他方式來獲得充氣器。如果你需要通過一個對象來控制inflater,你可以通過下面的例子來實例化它:mInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);然後調用mInflater.inflate(R.layout.layout2,this,false); – askilondz

0

您可能會考慮尋找HERE。您可以創建佈局,並通過在XML使用include重用他們在不同的佈局

2

可以從佈局2通過第一膨脹它作爲訪問一個元素如下:

LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); 
    LinearLayout layout = (LinearLayout)inflater.inflate(R.layout.layout2, null); 
    //or View view = (View)inflater.inflate(R.layout.layout2, null); 
    Button button = (Button)layout.findViewById(R.id.button1); 
    //add code for button