Header Ads

RadioButton

• A radio button is a two-states button that can be either checked or unchecked
 • When the radio button is unchecked, the user can press or click it to check it 
• Radio buttons are normally used together in a RadioGroup. 
• When several radio buttons live inside a radio group, checking one radio button uncheck all the others.
 • RadioButton inherits from … TextView. Hence, all the standard TextView properties for font face, style, color, etc. are available for controlling the look of radio buttons.
 • Similarly, you can call isChecked() on a RadioButton to  see if it is selected, toggle() to select it, and so on, like you can with a CheckBox. 

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RadioGroup
        android:id="@+id/radioSex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>

    <Button
        android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_display" />

</LinearLayout> 
 
 
MyAndroidAppActivity.java
 
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 MyAndroidAppActivity extends Activity {

  private RadioGroup radioSexGroup;
  private RadioButton radioSexButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.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(MyAndroidAppActivity.this,
    radioSexButton.getText(), Toast.LENGTH_SHORT).show();

  }

 });

  }
}  

No comments

Powered by Blogger.