且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的动态地从布局XML加元

更新时间:2023-10-27 21:41:04

 查看视图= LayoutInflater.from(上下文).inflate(R.layout.my_layout);
Button按钮=(按钮)view.findViewById(R.id.myButton);
....
aGroupView.addView(按钮);
 

How can I take the element myButton from this layout 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>

and put it on the layout of my choice (via code) ?

** solution (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);

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