• Latest Code...

    How to creating dynamically or programmatically radio buttons in Android

    Are you trying to create programmatically radio buttons on android, here is the tutorials may be helpful for you .

    Here is the full code:

    public class MainActivity extends Activity {
    private Button btnWrite;
    private LinearLayout ll;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    btnWrite= new Button(getApplicationContext());
    btnWrite.setText("ADD Radio Button");
    ll= new LinearLayout(getApplicationContext());
    btnWrite.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    createDynamicButton();
    }
    });

    ll.addView(btnWrite);
    setContentView(ll);
    }
    protected void createDynamicButton() {

    final RadioButton[] rb = new RadioButton[5];
       final RadioGroup rg = new RadioGroup(this); //create the RadioGroup
       rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
       for(int i=0; i<5; i++){
           rb[i]  = new RadioButton(this);
           rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
           rb[i].setText("Radio " + i);
       }
       ll.addView(rg);//you add the whole RadioGroup to the layout
       btnWrite.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
               for(int i = 0; i < 5; i++) { 
                   rg.removeView(rb[i]);//now the RadioButtons are in the RadioGroup
               }  
           }
       });

    }

    }

    Output snapshots of above code:





    Happy Codding !!!

    Circle

    Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace