2011-08-02 49 views
9

我如何可以從這個佈局XML的Android動態地從佈局XML元素添加

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <Button android:layout_width="wrap_content" android:text="Button" android:layout_height="wrap_content" android:id="@+id/myButton"></Button> 
</LinearLayout> 

元素爲myButton並把它放在我選擇的佈局(通過代碼)?

**溶液(THX aromero)**

LinearLayout view = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.my_button, null); 
// or LinearLayout buttonView = (LinearLayout)this.getLayoutInflater().inflate(R.layout.my_button, null); 
Button myButton = (Button) view.findViewById(R.id.myButton); 
view.removeView(myButton); 

LinearLayout mainView = (LinearLayout)this.findViewById(R.id.mainLayout); 
mainView.addView(myButton); 

回答

2
View view = LayoutInflater.from(context).inflate(R.layout.my_layout); 
Button button = (Button) view.findViewById(R.id.myButton); 
.... 
aGroupView.addView(button); 
+0

哦,哥們,那麼近。我終於用你的一部分得到了它。檢查最新的編輯。 – Jacksonkr

0

需要問R.id.mainLayout線性佈局在其他的XML文件或相同?