1

我有一個自定義視圖(擴展視圖),我想在OnCreate函數中添加控件(按鈕/文本框等),以在運行時將這些組件添加到視圖中:將表單組件添加到自定義android視圖

public Section(Context context) { 
    super(context); 

    this.setBackgroundColor(Color.argb(255, 242, 242, 242)); 
    this.setOnTouchListener(mSectionOnTouch); 

    LinearLayout l = new LinearLayout(this.getContext()); 
    l.setOrientation(LinearLayout.VERTICAL); 
    Button btn = new Button(this.getContext()); 
    btn.setId(1); 
    btn.setText("btn1"); 
    l.addView(btn); 

    Button btn2 = new Button(this.getContext()); 
    btn2.setId(2); 
    btn2.setText("btn2"); 
    l.addView(btn2); 

} // Section 

但這似乎沒有做任何事情......有人能告訴我什麼即時做錯了嗎?

非常感謝

FR

回答

0

你從不添加l到您的視圖。它應該是這樣的:

public Section(Context context) 
{ 
    // setup linear layout 

    addView(l); 
} 

一個稍微簡單的方式做這將是具有自定義視圖擴展的LinearLayout。然後,您可以直接將視圖添加到自定義視圖中,而不必嵌套另一個容器,這對性能更好。

+0

擴展LinearLayout而不是查看它 - 乾杯:D – FiniteRed

相關問題