top of page

Learn Android App Dev: Using Radiobuttons

Hey guys! This is Amey Lokhande. In this post I'll be guiding you on how to use Radiobuttons in your app. Well, the basic difference between Check boxes and RadioButtons is that Check boxes are used when you want to select multiple items from a list and Radio buttons are used when you want to select only One item from a list of items.

Here are the steps on how to use Radio buttons in your app:

1) First of all, drag a radio group from the containers in your layout. Then drag Radio Buttons from the widgets to your layout. Also drag a button which will be used to show the selected radio button. Remember that you have to drag your Radio Buttons in the Radio Group. So your app will look like:

2. Now the Java Code for making the app work:

i) First of all, declare the RadioGroup, RadioButton and a button in your MainActivity class.

ii) Then create a method which we will use to show the Toast message of the selected Radio Button. In that method, cast the RadioGroup and Buttons created.

iii) Then create a SetOnClickListener method for the button and in it declare variable for getting the id of the selected RadioButton. Use the RadioButton variable to link with the id of the selected RadioButton.

iv) Display the toast message using this RadioButton Variable.

So, your Show Toast method code will somewhat look like this:

A word of Caution: Here a = (RadioButton)findViewById(my_id);

which is not equal to a = (RadioButton)findViewById(R.id.my_id);

As you cannot put R.id.my_id while assigning the id to RadioButton.

So everything's done! Time to Run the code.

Screenshot of the Running App:

Java Code:

package com.example.ameylokhande.newapp;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast;

public class MainActivity extends AppCompatActivity { private static RadioGroup radio_g; private static RadioButton a; private static Button btn;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ShowToast(); } public void ShowToast(){ radio_g = (RadioGroup)findViewById(R.id.radiogroupid); btn = (Button)findViewById(R.id.button);

btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ int my_id = radio_g.getCheckedRadioButtonId(); a = (RadioButton)findViewById(my_id); Toast.makeText(MainActivity.this, a.getText().toString(), Toast.LENGTH_SHORT).show(); } }); } }

Thanks for reading the post! Stay Tuned!!

bottom of page