Radio Buttons: Java Source Code

import android.widget.RadioButton;
A radio button is a two-states button that can be either checked or unchecked.

import android.widget.RadioGroup;
This class is used to create a multiple-exclusion scope for a set of radio buttons. Checking one radio button that belongs to a radio group unchecks any previously checked radio button within the same group.

import android.widget.Toast;
A toast is a view containing a quick little message for the user. When the view is shown to the user, appears as a floating view over the application.

int selectedId = radioSexGroup.getCheckedRadioButtonId( );
Return the identifier of the selected radio button in this group.

Toast.makeText( MainActivity.this,
      radioSexButton.getText( ), Toast.LENGTH_LONG ).show( );
Make a standard toast that just contains a text view with the text from a resource.
Selecting
Female &

pushing
DISPLAY


MyApplication/app/src/main/java/com/example/wenchen/myapplication/MainActivity.java
01package com.example.wenchen.myapplication;
02 
03import android.app.Activity;
04import android.os.Bundle;
05import android.view.View;
06import android.view.View.OnClickListener;
07import android.widget.Button;
08import android.widget.RadioButton;
09import android.widget.RadioGroup;
10import android.widget.Toast;
11 
12public class MainActivity extends Activity {
13  private RadioGroup  radioSexGroup;
14  private RadioButton radioSexButton;
15  private Button      btnDisplay;
16 
17  @Override
18  public void onCreate( Bundle savedInstanceState ) {
19    super.onCreate( savedInstanceState );
20    setContentView( R.layout.activity_main );
21    addListenerOnButton( );
22  }
23 
24  public void addListenerOnButton( ) {
25    radioSexGroup = (RadioGroup) findViewById( R.id.radioSex );
26    btnDisplay    = (Button)     findViewById( R.id.btnDisplay );
27    btnDisplay.setOnClickListener( new OnClickListener( ) {
28      @Override
29      public void onClick( View v ) {
30        // Get selected radio button from radioGroup.
31        int selectedId = radioSexGroup.getCheckedRadioButtonId( );
32        // Find the radiobutton by returned id.
33        radioSexButton = (RadioButton) findViewById( selectedId );
34        Toast.makeText( MainActivity.this,
35          radioSexButton.getText( ), Toast.LENGTH_LONG ).show( );
36      }
37    });
38  }
39}