我有以下 axml。
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="360dp"
android:id="@+id/viewA">
<View
android:layout_width="wrap_content"
android:layout_height="360dp"
android:id="@+id/viewB" />
</LinearLayout>
我想以编程方式在 ViewB
上添加一个按钮。我无法弄清楚,因为 View
没有 addView
方法。
最佳答案
使用 FrameLayout 而不是 View。 View 没有 child 。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewA"
android:layout_width="wrap_content"
android:layout_height="360dp">
<FrameLayout
android:id="@+id/viewB"
android:layout_width="wrap_content"
android:layout_height="360dp" />
</LinearLayout>
只需添加您的代码:
Button button = new Button(this);
button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
FrameLayout group = (FrameLayout) findViewById(R.id.viewB);
group.addView(button);
关于android - 在 View 上添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735115/