This tutorial will show how to use Radio Buttons and Radio Groups in Android Studio. This app will have three Radio Buttons placed within a Radio Group. The user will have three options to choose from, when a user selects an option it will prompt a Toast Message displaying the user’s choice.
activity_main.xml
This is the layout of the app. There are three Radio Buttons that are placed within a Radio Group.
<LinearLayout 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="match_parent"
android:layout_height="150dp"
android:layout_marginTop="200dp">
<RadioButton
android:id="@+id/radioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="100dp"
android:layout_marginTop="10dp"
android:text="Option One"
android:textColor="#0423ED"
android:onClick="checked"/>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="100dp"
android:layout_marginTop="10dp"
android:text="Option Two"
android:textColor="#F60202"
android:onClick="checked"/>
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="100dp"
android:layout_marginTop="10dp"
android:text="Option Three"
android:textColor="#42B603"
android:onClick="checked"/>
</RadioGroup>
</LinearLayout>
MainActivity.Java
This portion of code is the function of the app. Here is how it works, once a user clicks on of the Radio Buttons in the group the function gets the ID of the button that was selected. From there it gets the Text from the button and then displays that Text in a Toast Message.
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
}
/// OnClick Method for when the button is clicked
public void checked(View v) {
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = findViewById(radioId);
Toast.makeText(this, "You Selected:" + radioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}