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
package com.example.wenchen.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
  private RadioGroup  radioSexGroup;
  private RadioButton radioSexButton;
  private Button      btnDisplay;

  @Override
  public void onCreate( Bundle savedInstanceState ) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );
    addListenerOnButton( );
  }

  public void addListenerOnButton( ) {
    radioSexGroup = (RadioGroup) findViewById( R.id.radioSex );
    btnDisplay    = (Button)     findViewById( R.id.btnDisplay );
    btnDisplay.setOnClickListener( new OnClickListener( ) {
      @Override
      public void onClick( View v ) {
        // Get selected radio button from radioGroup.
        int selectedId = radioSexGroup.getCheckedRadioButtonId( );
        // Find the radiobutton by returned id.
        radioSexButton = (RadioButton) findViewById( selectedId );
        Toast.makeText( MainActivity.this,
          radioSexButton.getText( ), Toast.LENGTH_LONG ).show( );
      }
    });
  }
}