Android 动态从布局 XML 添加元素

10

如何从此布局xml中获取myButton元素?

<?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>

我该如何把它放到我选择的布局中(通过代码)?

** 解决方案(感谢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个回答

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

哦,伙计,太接近了。我终于用了你的一部分来完成它。请检查最新的编辑。 - Jacksonkr

0

需要询问R.id.mainLayout的LinearLayout是在其他xml文件中还是在同一个文件中?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接