How to add radio button dynamically as per the given number of counts?

87,970

Solution 1

Please find below the code, I have created an 'EditText' and a 'Button' in the xml layout. Input a number in the 'EditText' and click the Button , The same no. of radio buttons will be added in the Layout.

This is your ActivityMain

public class ActivityMain extends AppCompatActivity implements View.OnClickListener {

    EditText mEtNumOfRadioBtns;
    Button mBtnAdd;
    String TAG = "TestActivity";
    RadioGroup mRgAllButtons;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        mEtNumOfRadioBtns = findViewById(R.id.et_no);
        mBtnAdd = findViewById(R.id.btn);
        mRgAllButtons = findViewById(R.id.radiogroup);
        //
        mBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number = Integer.parseInt(mEtNumOfRadioBtns.getText().toString().trim());
                addRadioButtons(number);
            }
        });
    }

    public void addRadioButtons(int number) {
        mRgAllButtons.setOrientation(LinearLayout.HORIZONTAL);
        //
        for (int i = 1; i <= number; i++) {
            RadioButton rdbtn = new RadioButton(this);
            rdbtn.setId(View.generateViewId());
            rdbtn.setText("Radio " + rdbtn.getId());
            rdbtn.setOnClickListener(this);
            mRgAllButtons.addView(rdbtn);
        }
    }

    @Override
    public void onClick(View v) {
        Log.d(TAG, " Name " + ((RadioButton)v).getText() +" Id is "+v.getId());
    }
}

And here is your layout file with name 'activity_main'

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" />

    <LinearLayout
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <EditText android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:hint="Enter no."
            android:inputType="number"
            android:id="@+id/et_no"/>

        <Button
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Add Radio btn"
            android:id="@+id/btn"/>

    </LinearLayout>
    
</RelativeLayout>

Solution 2

Try something like below:

RadioGroup rgp= (RadioGroup) findViewById(R.id.radiogroup);
RadioGroup.LayoutParams rprms;

for(int i=0;i<3;i++){
      RadioButton radioButton = new RadioButton(this);
      radioButton.setText("new"+i);
      radioButton.setId(View.generateViewId());
      rprms= new RadioGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      rgp.addView(radioButton, rprms);
}

Solution 3

This is the way to do this:

    RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);        
    int buttons = 5;
    for (int i = 1; i <= buttons ; i++) {
        RadioButton rbn = new RadioButton(this);
        rbn.setId(View.generateViewId());
        rbn.setText("RadioButton" + i);
        rgp.addView(rbn);
    }

enter image description here

But what if you need to do this horizontally, just add the orientation (the default value is vertical) with setOrientation() method:

    RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
    rgp.setOrientation(LinearLayout.HORIZONTAL);
    int buttons = 5;
    for (int i = 1; i <= buttons; i++) {
        RadioButton rbn = new RadioButton(this);
        rbn.setId(View.generateViewId());
        rbn.setText("RadioButton" + i);
        rbn.setLayoutParams(params);
        rgp.addView(rbn);
    }

enter image description here


This is the complete code:

first of all defining inside our Layout the RadioGroup:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</RelativeLayout>

The code into the MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Defining 5 buttons.
        int buttons = 5;
        AppCompatRadioButton[] rb = new AppCompatRadioButton[buttons];

        RadioGroup rgp = (RadioGroup) findViewById(R.id.radio_group);
        rgp.setOrientation(LinearLayout.HORIZONTAL);

        for (int i = 1; i <= buttons; i++) {
            RadioButton rbn = new RadioButton(this);
            rbn.setId(View.generateViewId());
            rbn.setText("RadioButton" + i);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);
            rbn.setLayoutParams(params);
            rgp.addView(rbn);
        }

    }
}

Solution 4

Add a Button and EditText in xml and take input from editText to variable inputValue and try this,

public class MyActivity extends Activity {

    /**
     * Called when the activity is first created.
     */
    LinearLayout ll=null;
    ViewGroup   vwgroup;
    Button btnClick;    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        vwgroup=((ViewGroup)findViewById(R.id.radiogroup)
        btnClick=(Button)findViewById(R.id.button1);


        btnClick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(ll!=null)
                    viewgroup.removeView(ll);
                ll = new LinearLayout(this);
                for(int i = 1; i < inputValue; i++) {
                    RadioButton rdbtn = new RadioButton(this);
                    rdbtn.setId(View.generateViewId());
                    rdbtn.setText("Radio " + rdbtn.getId());
                    ll.addView(rdbtn);
                }
                vwgroup.addView(ll);

            }
        });
    }
}
Share:
87,970
Dinesh Kumar
Author by

Dinesh Kumar

Learning in Java, Android and iOS

Updated on October 12, 2020

Comments

  • Dinesh Kumar
    Dinesh Kumar over 3 years

    I have tried this code..It will display three radio buttons in a single row when the emulator starts. But I need a button event for this. i.e; if I click the button, it should ask for number of radio buttons. then If I give the count, it must display the radio buttons based on the count given. For example, If I give the count as 3, it must display the three radio buttons in a single row. Your help is highly appreciated. Thanks in advance.

      public class MyActivity extends Activity {
        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            for(int row=0; row < 1; row++)
            {
                LinearLayout ll = new LinearLayout(this);
                ll.setOrientation(LinearLayout.HORIZONTAL);
                for(int i = 1; i < 4; i++) {
                    RadioButton rdbtn = new RadioButton(this);
                    rdbtn.setId((row * 2) + i);
                    rdbtn.setText("Radio " + rdbtn.getId());
                    ll.addView(rdbtn);
                }
                ((ViewGroup)findViewById(R.id.radiogroup)).addView(ll);
            }
        }
        }
    

    this is xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    tools:context=".MainActivity" >
    
        <RadioGroup
                android:id="@+id/radiogroup"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"/>
    
        </RelativeLayout>
    
  • syr
    syr almost 9 years
    Just in case someone stumbles upon the same problem: I tried this solution, however with the shown hierarchy (radiogroup->linearlayout->radiobutton) I didn't get the checked radiobutton by: ((RadioGroup)findViewById(R.id.radiogroup)).getCheckedRadioB‌​uttonId(); I needed to switch the linearlayout so that the radiobutton is direclty added to the radiogroup like (linearlayout->radiogroup->radiobutton).
  • Mohammad Zekrallah
    Mohammad Zekrallah over 8 years
    this works fine but allows for multiple radio buttons to be checked in the same time ! to prevent this, just don't add the radio buttons to the linear layout, add directly to the radio button's group.
  • Ninja Coding
    Ninja Coding over 8 years
    @MohammadZekrallah, you right, this allow multi-select, radio supposed to be "single" select. thank you man. Answer should be updated.
  • Ayush Pateria
    Ayush Pateria about 8 years
    Won't this create a RadioGroup inside a RadioGroup?
  • Goke Obasa
    Goke Obasa over 7 years
    Thanks for this. One thing to note is that the id has to be unique, this was the issue I was having.
  • Jorgesys
    Jorgesys over 7 years
    yes of course with (1 + 1000) the id is a consecutive number defined for the id : rbn.setId(1 + 1000);
  • Karan Thakkar
    Karan Thakkar almost 7 years
    I want to map the buttons horizontally but the above solution doesn't seem to work for me. It works if I want to map it vertically but not horizontally. Any help?
  • Gowthaman M
    Gowthaman M over 6 years
    @Riser How to get text from the selected radio button please help me
  • nikeru8
    nikeru8 over 6 years
    how to add Click event for each radioButton ?
  • nikeru8
    nikeru8 over 6 years
    How to get Click event for each RadioButton?
  • William
    William almost 6 years
    This is by far the easiest way for me
  • Adarsh Vijayan P
    Adarsh Vijayan P almost 6 years
    @nikeru8 set click event for button: // get selected radio button from radioGroup int selectedId = radioSexGroup.getCheckedRadioButtonId(); // find the radiobutton by returned id **radioSexButton** = (RadioButton) findViewById( **selectedId** ); **radioSexButton**.setOnClick...... Toast.makeText(MyAndroidAppActivity.this, _radioSexButton.getText()_, Toast.LENGTH_SHORT).show();
  • Gayathri
    Gayathri over 5 years
    my question is, how to set (setChecked = true) only for RadioButton3. - Jorgesys
  • Freek de Bruijn
    Freek de Bruijn over 5 years
    For API level 17+, you can call View.generateViewId() -- from stackoverflow.com/a/35551268/1694043
  • Freek de Bruijn
    Freek de Bruijn over 5 years
    For API level 17+, you can call View.generateViewId() -- from stackoverflow.com/a/35551268/1694043
  • Freek de Bruijn
    Freek de Bruijn over 5 years
    For API level 17+, you can call View.generateViewId() -- from stackoverflow.com/a/35551268/1694043
  • Freek de Bruijn
    Freek de Bruijn over 5 years
    For API level 17+, you can call View.generateViewId() -- from stackoverflow.com/a/35551268/1694043
  • Jitender Dev
    Jitender Dev over 4 years
    I have added click events for radio buttons.
  • Mohammed Deifallah
    Mohammed Deifallah almost 4 years
    @GowthamanM I hope this question is useful for your case.