我必须动态地将CheckBox添加到我的Activity布局中,布局的XML如下所示
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parentSV"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/parentLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<RelativeLayout
android:id="@+id/feedbackRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/feedbackCustomerNameLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Name : "
android:textColor="@android:color/black" />
<TextView
android:id="@+id/feedbackCustomerName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textColor="@android:color/black" />
</LinearLayout>
<LinearLayout
android:id="@+id/feedbackPlansLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/feedbackCustomerNameLL"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Plans Explained"
android:textColor="@android:color/black" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/feedbackPlansCheckBoxLL"
android:orientation="horizontal" >
<!--
Required to Add CheckBoxes Here Dynamically
-->
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)
`
CheckBoxes将添加到注释区域中.如何动态添加它们,因为我必须根据服务器发送的数据在运行时添加它们.我无法从层次结构中删除ScrollView或任何其他视图.
给那个布局一个id......
<LinearLayout
android:id="@+id/check_add_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/feedbackPlansCheckBoxLL"
android:orientation="horizontal" >
<!--
Required to Add CheckBoxes Here Dynamically
-->
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
使用给定的id初始化父布局为...
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.check_add_layout);
Run Code Online (Sandbox Code Playgroud)
然后创建你的CheckBox ...
CheckBox checkBox = new CheckBox(this);
checkBox.setId(id);
checkBox.setText("text");
Run Code Online (Sandbox Code Playgroud)
创建有关其大小,填充,对齐的参数...
LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
checkParams.setMargins(10, 10, 10, 10);
checkParams.gravity = Gravity.CENTER;
Run Code Online (Sandbox Code Playgroud)
现在将新创建的内容添加CheckBox到该父布局中...
parentLayout.addView(checkBox, checkParams);
Run Code Online (Sandbox Code Playgroud)