multiple radio groups with only one allowed selection? - android

For layout purposes I have three radiogroups with multiple selections in each group. How can I code so that only one choice is allowed, across all three groups?
In other words, right now I can make a selection in each group for a total of 3 selections. I want these to "see" each other and only allow one selection total.

Here's the method:
private RadioButton lastCheckedRB = null;
//whatever code
//onClicklistener for radiogroup does not work
RadioGroup.OnCheckedChangeListener listener = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
//OnCheckedChangeListener checks for reclick of a clicked rb, so the rest of the code is not executed
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
//store the clicked radiobutton
lastCheckedRB = checked_rb;
}
};
radioGroup1.setOnCheckedChangeListener(listener);
radioGroup2.setOnCheckedChangeListener(listener);

Related

Android -get radio button id based on value

I want to highlight right and wrong option when user clicks a button after checking an radio button. If that option is right, highlight. Else highlight right option.
Is there any way to get radio button id in a group based on its value? Or Do I need to use switch case?
I searched enough but not able to find out what I need.
Edit
I have simple layout which contains one question, 4 choices, one button. User check a radio button and click the check button. If user selects wrong option, highlight the correct option. I know what is correct option by value.
choice1, choice2, choice3, choice4 are four radio buttons. User checks choice3. But choice2 is correct. How do I select choice2 by value in this radio group.
group.getRadioButtonId("choice2")
Anything similar to this?
You could iterate through the children of your RadioGroup to get the required one:
int count = radioGroup.getChildCount();
for (int i = 0 ; i < count; i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
if (button.getText().equals("choice2")) {
int id = button.getId(); // the ID you're looking for
}
}
You Can check like this
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int rbId = group.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rbId);
switch (group.getId()) {
case R.id.radiogroupID:
if (rb.getText().toString().equalsIgnoreCase("right")) {
// your logic
} else {
//your logic
}
}
}
you can use these line. its working for me
int checkedId = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(checkedId);
int radioId = radioGroup.indexOfChild(radioButton);
RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
First check which option is true. hear choice 2 OK. set by default is checked true and than check user checked value . if user select other option than display message and pass true option we already checked true
Create an int array with all the ids of the radiobutton
int[] rb_IDs=new int[]{R.id.rb1,R.id.rb2,R.id.rb3};
Then inside your button click :
RadioGroup rg=(RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i=0;i<rb_IDs.length;i++)
{
RadioButton rb=(RadioButton)findViewById(rb_IDs[i]);
if (rb.getText().toString().equals("YOUR CORRECT ANSWER")&&!rb.isChecked())
{
//
//Do your thing
//
//ID of the correct answer Radiobutton is
int id=rb_IDs[i];
//HighLighting the answer
rb.setBackgroundColor(Color.parseColor("#00ff00"));
break;
}
}
}
});

How to get radio Button values number

I am making an application that has list and Radio Buttons. My Layout contains of the following : a list , A button .
The List contains of Radio buttons. Two radio Buttons. After checking the buttons. I want to make a loop that reads the values of how many are in Button one and how many in Button Two.
This is how I have done so far.
ListViewStudentEditAbsence country ;
for(int i=0;i<listViewStudentNames.size();i++) {
country = listViewStudentNames.get(i);
if (country.getAbsence()==1) {
Absence[i] = "1";
} else {
Absence[i] ="0";
}
}
But It doesn't seem to work.
In your CustomAdapter getView() method
int value=0; //globally
RadioGroup radioGroup = (RadioGroup) convertView.findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
if (checkedId == R.id.rbutton1) {
value=10; //a's value
} else if (checkedId == R.id.rbutton2) {
value=20; //b's value
}
}
});
https://stackoverflow.com/questions/11194515/android-get-value-of-the-selected-radio-button
Android getting value from selected radiobutton
Hope it works. This two links give you proper knowledge about fetching value.

How to add a listener to dynamically created RadioButtons?

I have a ListView of questions. In each row there is a question and a RadioGroup with possibile answers. Not all the questions have the same number of answers, so I add the RadioButtons dynamically in my custom ListAdapter. My question is how to add Listener to these dynamically created RadioButtons. My code:
RadioGroup rg = (RadioGroup) convertView.findViewById(R.id.question);
rg.removeAllViews();
for (String qA : question.answers) {
RadioButton rb = new RadioButton(getContext());
rb.setText(qA.toString());
rg.addView(rb);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId) {
//WHAT SHOULD I PUT HERE?
}
}
});
Maby something like this:
#Override public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton btn = (RadioButton)findViewById(checkedId);
}
and then something with the btn? :)
To find the checked button
View checkedButton = rg.findViewById(checkedId);
To find the index of checked button
int checkedIndex = rg.indexOfChild(checkedButton);
Before doing the above you have to set id to the buttons like mentioned in the comments rb.setId(count). Count has to be unique for each button within a group.
1 first create global variable of CompoundButton.OnCheckedChangeListener in your adapter for example private CompoundButton.OnCheckedChangeListener listener
2 second you have to attach listener variable with your radio button at the time of creating the radio button.
3 third when you bind the data or value with your ui you have to call this method
listener = new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged ( CompoundButton buttonView, boolean isChecked )
{
}
};

How to force RadioGroup to select only one RadioButton at a time programatically?

I am designing customize form programmatically where user can put a question and can add multiple options using radio buttons. I have taken RadioGroup and i am adding radio buttons in it. But while selecting i want only one radio button get selected at a time. How to implement it programmatically. Please help me..
Here is my code
final RadioGroup radioGroup = new RadioGroup(getApplicationContext());
radioGroup.setId(1);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
RadioButton radioButtonView = new RadioButton(getApplicationContext());
radioButtonView.setId(i++);
radioButtonView.setText(addnew);
radioGroup.addView(radioButtonView, p);
loption.addView(radioGroup, p);
Thanks in advance,
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "onCheckedChanged " + buttonView.getId());
mRadioGroup.clearCheck();
if (isChecked) {
mRadioGroup.check(buttonView.getId());
}
}
It seems that you are making a new RadioGroup for every RadioButton.
You should add every new RadioButton to the same RadioGroup. The RadioGroup will then make sure only one RadioButton can be selected at the time.
I have tried the same problem when I insert LinearLayout to put the radiobuttons in a grid.
I solved this way.
Considering that we have more RadioGroups, we know the RadioButton that was pressed. For this reason, just remove the listener from all of your RadioGroups and then deselect all the RadioButtons, resetting onCheckedChangeListener to your RadioGroup.
This is my code:
onCheckedChangeListener= new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
clearAllRadioButton();
((RadioButton) binding.getRoot().findViewById(i)).setChecked(true);
resetListenerRadioGroup();
}
};
onCheckedChangeListener2 = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
clearAllRadioButton();
((RadioButton) binding.getRoot().findViewById(i)).setChecked(true);
resetListenerRadioGroup();
}
};
binding.rg.setOnCheckedChangeListener(onCheckedChangeListener);
binding.rg2.setOnCheckedChangeListener(onCheckedChangeListener2);
private void clearAllRadioButton() {
binding.rg2.setOnCheckedChangeListener(null);
binding.rg.setOnCheckedChangeListener(null);
binding.failed.setChecked(false);
binding.draft.setChecked(false);
binding.sent.setChecked(false);
binding.inbox.setChecked(false);
}
private void resetListenerRadioGroup(){
binding.rg2.setOnCheckedChangeListener(onCheckedChangeListener2);
binding.rg.setOnCheckedChangeListener(onCheckedChangeListener);
}
*do not use the radioButton's clearCheck () because it does not respond well when resetting listeners.
Check this out it will work for you:
First Get RadioButton:
RadioButton radioBalls = (RadioButton) findViewById(R.id.radioGameInPlayBalls);
RadioButton radioTime = (RadioButton) findViewById(R.id.radioGameInPlayTime);
radioBalls.setOnCheckedChangeListener(this);
radioTime.setOnCheckedChangeListener(this);
Now in #overide method:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean c) {
switch (buttonView.getId()) {
case R.id.radioGameInPlayBalls:
if (radioTime.isChecked() && c) {
radioBalls.setChecked(false);
return;
}
radioBalls.setEnabled(c);
break;
case R.id.radioGameInPlayTime:
if (radioBalls.isChecked() && c) {
radioTime.setChecked(false);
return;
}
radioTime.setEnabled(c);
break;
default:
break;
}
}
You should check a radio button using RadioGroup, not radio button directly. Below, I populate radio group from list of options and get the radio button id of option to be checked and check the corresponding button after populating radio group. Same goes if you determine the checked option by index.
int checkedId = -1;
for(JsonElement option : options){
RadioButton radioButton = new RadioButton(getContext());
radioGroup.addView(radioButton);
if(checkedOptionId.equals(id)){
checkedId = radioButton.getId();
}
}
radioGroup.check(checkedId);

How to set OnClickListener on a RadioButton in Android?

I have two RadioButtons inside a RadioGroup. I want to set OnClickListener on those RadioButtons. Depending on which RadioButton is clicked, I want to change the text of an EditText. How can I achieve this?
I'd think 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
}
});
Hope this will help you...
RadioButton rb = (RadioButton) findViewById(R.id.yourFirstRadioButton);
rb.setOnClickListener(first_radio_listener);
and
OnClickListener first_radio_listener = new OnClickListener (){
public void onClick(View v) {
//Your Implementaions...
}
};
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
RadioButton rb=(RadioButton)findViewById(checkedId);
textViewChoice.setText("You Selected " + rb.getText());
//Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show();
}
});
The question was about Detecting which radio button is clicked, this is how you can get which button is clicked
final RadioGroup radio = (RadioGroup) dialog.findViewById(R.id.radioGroup1);
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radio.findViewById(checkedId);
int index = radio.indexOfChild(radioButton);
// Add logic here
switch (index) {
case 0: // first button
Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
break;
case 1: // secondbutton
Toast.makeText(getApplicationContext(), "Selected button number " + index, 500).show();
break;
}
}
});
For Kotlin Here is added the lambda expression and Optimized the Code.
radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
run {
when (optionId) {
R.id.radioButton1 -> {
// do something when radio button 1 is selected
}
R.id.radioButton2 -> {
// do something when radio button 2 is selected
}
// add more cases here to handle other buttons in the your RadioGroup
}
}
}
Hope this will help you. Thanks!
You could also add listener from XML layout: android:onClick="onRadioButtonClicked" in your <RadioButton/> tag.
<RadioButton android:id="#+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pirates"
android:onClick="onRadioButtonClicked"/>
See Android developer SDK- Radio Buttons for details.
Since this question isn't specific to Java, I would like to add how you can do it in Kotlin:
radio_group_id.setOnCheckedChangeListener({ radioGroup, optionId -> {
when (optionId) {
R.id.radio_button_1 -> {
// do something when radio button 1 is selected
}
// add more cases here to handle other buttons in the RadioGroup
}
}
})
Here radio_group_id is the assigned android:id of the concerned RadioGroup. To use it this way you would need to import kotlinx.android.synthetic.main.your_layout_name.* in your activity's Kotlin file. Also note that in case the radioGroup lambda parameter is unused, it can be replaced with _ (an underscore) since Kotlin 1.1.
Just in case someone else was struggeling with the accepted answer:
There are different OnCheckedChangeListener-Interfaces. I added to first one to see if a CheckBox was changed.
import android.widget.CompoundButton.OnCheckedChangeListener;
vs
import android.widget.RadioGroup.OnCheckedChangeListener;
When adding the snippet from Ricky I had errors:
The method setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener) in the type RadioGroup is not applicable for the arguments (new CompoundButton.OnCheckedChangeListener(){})
Can be fixed with answer from Ali :
new RadioGroup.OnCheckedChangeListener()
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnClickListener(v -> {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
String slectedValue=radioButton.getText()
});

Categories

Resources