Android Radion Button and Radio Group Tutorial

Radio Button use for give option to the user to select one single thing (option) from multiple thing (option). A radio button is a round circle representing choices in a common option list form in a graphical user interface.

For example, if we want to give option to user whether he/she is male/female, then we will use Radio Button to give option to user.

Step 1.

Create new application with any name from file menu option.

File → New Project → Application name → select API → Add Blank Activity → Activity Name → finish

Step 2.

In activity_main.xml layout file design your application.

Add following Controls:-

radio button tutorial

Step 3.

Import Package and write following coding in MainActivity.java class file.

	
    import android.view.View;
    import android.widget.Toast;
    import android.widget.Button;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.graphics.Color;

   import javax.xml.datatype.Duration;


  public class MainActivity extends ActionBarActivity {

    Color c;
    RadioButton r1,r2,r3;
    RadioGroup rg;
    Button b1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg=(RadioGroup)findViewById(R.id.rgd);
        r1=(RadioButton)findViewById(R.id.radioButton);
        r2=(RadioButton)findViewById(R.id.radioButton2);
        r3=(RadioButton)findViewById(R.id.radioButton3);
        b1=(Button)findViewById(R.id.button);
        b1.setOnClickListener(new View.OnClickListener() {
        @Override
            public void onClick(View v) {

            if(r1.isChecked() || r2.isChecked() || r3.isChecked()) {
                int sel = rg.getCheckedRadioButtonId();

                //b1.setBackgroundColor(Color.GREEN);
                r1 = (RadioButton) findViewById(sel);
      Toast.makeText(MainActivity.this, r1.getText(), Toast.LENGTH_LONG).show();
      }
      else
      {
      Toast.makeText(MainActivity.this,"Please select One",Toast.LENGTH_LONG).show();
            }
            }
        });
    }
    

Step 4. Final Output

Run your Application and click on any of the RadioButton. Toast message will display.

radio button tutorial

Post Your Comment