如何动态添加单选按钮,而不是丢失视图内容

时间:2011-03-27 20:25:31

标签: android radio-group

我的布局看起来像这样

    <?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="wrap_content">
        <TextView android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:textStyle="bold" 
            android:text="Please select the restaurant you want to rate: " />

        <RadioGroup android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/SelectRestaurant">

         </RadioGroup>
         <Button android:layout_width="100px"
         android:layout_height="wrap_content" 
         android:text="Rate it" 
         android:id="@+id/submitSelection"/>
</LinearLayout>

当我在java文件中将radiobuttons添加到radiogroup时,radiobuttons彼此重叠,并且提交按钮消失了。我猜radiobuttons正在覆盖其他视图元素。如何在不丢失其他元素的情况下动态添加这些单选按钮。

Java代码如下所示:

setContentView(R.layout.submit_select);
        RadioGroup radioGroup = (RadioGroup)findViewById(R.id.SelectRestaurant);
        for (String restaurant : restaurants) {
            RadioButton radioButton = new RadioButton(getBaseContext());
            radioButton.setText(restaurant);
            radioGroup.addView(radioButton);
        }
        radioGroup.invalidate();
        dismissDialog(DIALOG_SUBMIT_ID);
        rateItButton = (Button) findViewById(R.id.submitSelection);
        rateItButton.setOnClickListener(this);

1 个答案:

答案 0 :(得分:2)

尝试使用WRAP_CONTENT为宽度和高度创建布局参数,然后在将按钮添加到组时添加layoutParams:

radiogroup.addView(newRadioButton, layoutParams);