Radio Button Android Part 1 :- Check and Unchecked

Description From https://developer.android.com/guide/topics/ui/controls/radiobutton.html

Radio Buttons


Radio buttons allow the user to select one option from a set. You should use radio buttons for optional sets that are mutually exclusive if you think that the user needs to see all available options side-by-side. If it's not necessary to show all options side-by-side, use a spinner instead.

To create each radio button option, create a RadioButton in your layout. However, because radio buttons are mutually exclusive, you must group them together inside a RadioGroup. By grouping them together, the system ensures that only one radio button can be selected at a time.

1. Make a   XML Layout


<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.avadhesh.radiobutton.MainActivity">


    <RadioButton        android:id="@+id/radioButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="RadioButton" />
</RelativeLayout>
2. Coding
Within the Activity that hosts this layout, the following method handles the click event for  radio buttons: by which you can Check and Unchecked the radio button.
@Overridepublic void onClick(View v) {

    switch (v.getId())
    {
        case R.id.radioButton:
            if(radioButton.isSelected())
            {
                radioButton.setSelected(false);
                radioButton.setChecked(false);
            }else {
                radioButton.setSelected(true);
                radioButton.setChecked(true);
            }

            break;
    }

}

3. Output

 When radio button is not check.

When radio button is check.





No comments:

Post a Comment