Tuesday, August 19, 2014

Create RadioGroup Programmatically in Android

Create RadioGroup Programmatically in Android
This post about how to create radio group programmatically with multiple radio buttons.

Screen Shot



Activity Code
package com.vj.radiogroup;

import android.app.Activity;

import android.graphics.drawable.Drawable;

import android.os.Bundle;

import android.widget.RadioButton;

import android.widget.RadioGroup;

public class MainActivity extends Activity {

       String[] questions = { "Questions" };

       String[] answers = { "Answers 1", "Answers 2", "Answers 3", "Answers 4",
                     "Answers 5" };

       @Override
       protected void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              setContentView(R.layout.activity_main);

              RadioGroup rg = new RadioGroup(this);

              for (int i = 0; i < answers.length; i++) {

                     RadioButton radioBtn = new RadioButton(this);

                     Drawable img = getResources()
                                  .getDrawable(R.drawable.radiobtn_state);

                     radioBtn.setCompoundDrawablesWithIntrinsicBounds(null, null, img,
                                  null);

                     radioBtn.setCompoundDrawablePadding(23);

                     radioBtn.setText(answers[i]);

                     radioBtn.setButtonDrawable(android.R.color.transparent);

                     radioBtn.setId(i);

                     radioBtn.setTextSize(20);

                     rg.addView(radioBtn);

              }

              setContentView(rg);

       }

}

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...