41

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.

  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>
starball
  • 20,030
  • 7
  • 43
  • 238
Dinesh Kumar
  • 1,173
  • 7
  • 19
  • 30

4 Answers4

75

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>
David Buck
  • 3,752
  • 35
  • 31
  • 35
Jitender Dev
  • 6,907
  • 2
  • 24
  • 35
  • 1
    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)).getCheckedRadioButtonId(); I needed to switch the linearlayout so that the radiobutton is direclty added to the radiogroup like (linearlayout->radiogroup->radiobutton). – syr Jul 20 '15 at 14:52
  • 4
    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. – Mohammad Zekrallah Jan 03 '16 at 17:05
  • 1
    @MohammadZekrallah, you right, this allow multi-select, radio supposed to be "single" select. thank you man. Answer should be updated. – Ninja Coding Mar 22 '16 at 20:07
  • 2
    Won't this create a RadioGroup inside a RadioGroup? – Ayush Pateria Jun 05 '16 at 14:35
  • how to add Click event for each radioButton ? – nikeru8 Mar 15 '18 at 07:40
  • @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();` – Adarsh Vijayan P Sep 08 '18 at 10:41
  • For API level 17+, you can call View.generateViewId() -- from https://stackoverflow.com/a/35551268/1694043 – Freek de Bruijn Dec 27 '18 at 13:55
  • I have added click events for radio buttons. – Jitender Dev Jan 29 '20 at 07:40
27

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);
}
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
19

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);
        }

    }
}
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
1

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);

            }
        });
    }
}
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
Mukesh Kumar Singh
  • 4,512
  • 2
  • 22
  • 30