Jay.
Jay.

Reputation: 331

Get the checked radio button

I want to create dynamic RadioGroup (with dynamic radio options). I'm doing with the following code.

My question is that, how can I get the option that is selected by clicking the button "Check Answer". If the radio group is added through the XML layout then I can get by its ID, but in this case I'm unable to do so.

Here's the code:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/button">
    </LinearLayout>

    <TextView
        android:id="@+id/answer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/button"
        android:textColor="#008b00"
        />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Check Answer"
        app:layout_constraintBottom_toBottomOf="parent"
        android:onClick="checkAnswer"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity:

package com.example.quiz8;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private LinearLayout linearLayout = null;

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

        linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        RadioGroup radioGroup = new RadioGroup(this);
        RadioButton radioButton;

        final String[] title = {"Male", "Female", "Other", "Secret"};

        for (int i = 0; i < title.length; i++) {
            radioButton = new RadioButton(this);
            radioButton.setId(i);
            radioButton.setText(title[i]);
            radioGroup.addView(radioButton);
        }

        linearLayout.addView(radioGroup);
    }

    public void checkAnswer(View view) {
        //get the answer here
        TextView answerText = (TextView) findViewById(R.id.answer);
        answerText.setText("You selected the option...");
    }
}

Upvotes: 0

Views: 64

Answers (3)

Hanzla
Hanzla

Reputation: 284

1) You can add following code in OnClickListner() to check if desired check boxed is clicked.

// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radio_pirates:
        if (checked)
            // Pirates are the best
        break;
    case R.id.radio_ninjas:
        if (checked)
            // Ninjas rule
        break;
}

Further help can be found in Radio button documentation : Radio Button Documentation

2) Another method: A better way is to use RadioGroup and set the listener on this to change and update the View accordingly (saves you having 2 or 3 or 4 etc listeners).

RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);        
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() 
{
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // checkedId is the RadioButton selected
    }
});

Upvotes: 1

B&#246; macht Blau
B&#246; macht Blau

Reputation: 13009

You can set a tag to the RadioGroup in order to be able to find it easily. A tag can be any Object. We'll use a String here, which has to be unique in the ViewGroup on which you call findViewWithTag(). Then in checkAnswer() you retrieve the RadioGroup by its tag and so get the text of the checked RadioButton.

private static final String RADIOGROUP_TAG = "radiogroup";

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

    linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
    RadioGroup radioGroup = new RadioGroup(this);
    radioGroup.setTag(RADIOGROUP_TAG);

    RadioButton radioButton;

    final String[] title = {"Male", "Female", "Other", "Secret"};

    for (int i = 0; i < title.length; i++) {
        radioButton = new RadioButton(this);
        radioButton.setId(i);
        radioButton.setText(title[i]);
        radioGroup.addView(radioButton);
    }

    linearLayout.addView(radioGroup);
}

public void checkAnswer(View view) {
    //get the answer here
    RadioGroup radioGroup = linearLayout.findViewWithTag(RADIOGROUP_TAG);
    int checkedId = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = radioGroup.findViewById(checkedId);
    String text = radioButton.getText().toString();

    TextView answerText = (TextView) findViewById(R.id.answer);
    answerText.setText("You selected the option..." + text);
}

Another option: you can have String[] title and the RadioGroup as fields in your Activity. This makes sense since you need them in more than one place.

private final String[] title  = {"Male", "Female", "Other", "Secret"};
private RadioGroup radioGroup;

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

    linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
    radioGroup = new RadioGroup(this);

    RadioButton radioButton;

    for (int i = 0; i < title.length; i++) {
        radioButton = new RadioButton(this);
        radioButton.setId(i);
        radioButton.setText(title[i]);
        radioGroup.addView(radioButton);
    }

    linearLayout.addView(radioGroup);
}

public void checkAnswer(View view) {
    //get the answer here
    int checkedId = radioGroup.getCheckedRadioButtonId();
    TextView answerText = (TextView) findViewById(R.id.answer);
    // Note: make sure there is a checked RadioButton! 
    answerText.setText("You selected the option..." + title[checkedId]);
}

Upvotes: 1

Tomislav Emilov
Tomislav Emilov

Reputation: 11

You can simply check for the selected one.

public class MainActivity extends AppCompatActivity {

    private LinearLayout linearLayout = null;

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

        linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
        RadioGroup radioGroup = new RadioGroup(this);
        RadioButton radioButton;

        final String[] title = {"Male", "Female", "Other", "Secret"};

        for (int i = 0; i < title.length; i++) {
            radioButton = new RadioButton(this);
            radioButton.setId(i);
            radioButton.setText(title[i]);
            radioGroup.addView(radioButton);
            radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                //checkedId is the RadioButton selected
            }

        }

        linearLayout.addView(radioGroup);
    }

    public void checkAnswer(View view) {
        //get the answer here
        TextView answerText = (TextView) findViewById(R.id.answer);
        answerText.setText("You selected the option...");
    }
}

Upvotes: 1

Related Questions