How to dynamically add radiobuttons and not lose view contents

浪子不回头ぞ 提交于 2019-12-06 08:44:55

问题


My layout looks like this

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

When I add radiobuttons to the radiogroup in java file, radiobuttons are overlapping on each other and submit button is gone. I guess radiobuttons are overriding other elements of view. How can I dynamically add these radio buttons without losing other elements.

Java code looks like this:

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:


Try creating Layout Parameters with WRAP_CONTENT for the width and height and then adding the layoutParams when you add the button to the group:

radiogroup.addView(newRadioButton, layoutParams);


来源:https://stackoverflow.com/questions/5452155/how-to-dynamically-add-radiobuttons-and-not-lose-view-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!