2013-07-29 181 views
1

我有幾個自定義LinearLayout s,我想動態添加到Activity的主RelativeLayout。 這是我的自定義佈局之一:動態添加自定義佈局到活動的佈局

public class MyLayout1 extends LinearLayout {...} 

這是my_layout_1.xml文件吧:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); 
View view = getLayoutInflater().inflate(R.layout.my_layout_1, mainLayout, false); //mainLayout is the id of the main RelativeLayout 
mainLayout.addView(view, params); 

<?xml version="1.0" encoding="utf-8"?> 
<***myPackageName***.MyLayout1 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" > 
...... 
</***myPackageName***.MyLayout1> 

我使用此代碼的自定義佈局添加到RelativeLayout代碼工作正常。
但是,當我在我的自定義MyLayout1類中使用findViewById(...)函數時,它將爲所有視圖返回null。如何綁定.xml文件和Java類?我認爲在.xml中添加包+類名就夠了,但我錯了。 此外,我試圖呼叫

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View view = inflater.inflate(R.layout.my_layout_1, null); 

MyLayout1類,但android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>錯誤消息在登錄窗口中顯示。

+0

你的意思是findViewById()(no s) –

+0

你是如何得到你的類中的代碼?它在構造函數中嗎?在從其他地方調用的方法中? –

+0

O,是的。抱歉。我現在會改變它。 – smb

回答

1

如果您需要致電findViewById()以訪問那些你layout.xml文件內聲明的意見的情況下,那麼你需要做的這View#onfinishInflate()。一旦視圖完成膨脹,就會調用它。在該功能中,您可以成功使用findViewById()。在構造函數中使用findViewById()時,視圖被充氣後,子視圖將不會被實例化並添加。這就是爲什麼它返回null。

+0

非常感謝! – smb