How to group radio buttons programmatically in Java/Kotlin? - android

I have a custom view for radio buttons in the XML layout file with ConstraintLayout. I need to group those radio buttons. But when I try to envelop that ConstraintLayout with the Radio group, it does not group the buttons and all options are getting selected.

RadioButtons need to be the direct children of a RadioGroup in order for the grouping functionality to work. A RadioGroup is just a special LinearLayout that implements the grouping functionality for all the children added that are RadioButtons. You can simply implement your own grouping functionality by adding the RadioButtons to a List and then implementing OnCheckedChangeListener and setting it on each of the RadioButtons as follows:
private final List<RadioButton> radioButtons = new ArrayList<>();
private int checkedId;
private void setRadioButton(RadioButton radioButton) {
radioButtons.add(radioButton);
radioButton.setOnCheckedChangeListener(mOnCheckedChangeListener);
}
private final CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
checkedId = buttonView.getId();
}
for (RadioButton radioButton : radioButtons) {
if (radioButton.getId() != checkedId) {
radioButton.setChecked(false);
}
}
}
};

you can set false the checked of icon in the defult running like this code in layout
xml
android:checked="false"
and in coding you can call binding.rdiobutton.setonclicklistenert{
binding.btnclick.setonclicklistener)

Use the following code in kotlin
radioGroup.check(id)
First, you write the name of the radio group, then instead of the ID, put the ID of the radio button,
For example, it is like this in my project
rg_licenseType.check(R.id.rb_three)

Related

RadioButton Issue get checked when sending?

Having two RadioButtons and button send.
When I click on the send button the 2 RadioButtons are checked.
How to avoid this?
enter image description here
You need to group the radio buttons so inside the xml add the radio buttons inside this tag:
<RadioGroup> .....</RadioGroup>
then in your activity do this:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.myRadioGroup); //declare the radiogroup
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.radiobtn1) {
//code here
} else if(checkedId == R.id.radiobtn2) {
//code here
} else {
//code here
}
}
});
If you want only one RadioButton to be checked at once, keep them inside a RadioGroup.
Just Put your RadioButtons inside RadioGroup

Android: A specific RadioButton belongs to which RadioGroup?

Is it possible to identify for which Radio Group a specific Radio Button belongs to in Android?
Eg:
RadioGroup_A
- RadioButton_1A
- RadioButton_2A
RadioGroup_B
- RadioButton_1B
- RadioButton_2B
When I have RadioButton_1A, to idetify that belongs to RadioGroup_A ?
I need to implement a logic to ignore triggering CheckedChange listener for a speacial case. Need to restrict that only for a one RadioGroup When I know that RadioButton belongs to that specific RadioGroup.
Thanks
What about radioGroup.indexOfChild method? The doc says that returns:
a positive integer representing the position of the view in the group,
or -1 if the view does not exist in the group
Maybe you can check if your RadioButton exits in the RadioGroup:
int idx = radioGroup.indexOfChild(radioButton);
if (idx != -1)
{
//radioButton is in the radioGroup
}
else {
//radioButton isnt in the radioGroup
}
Hope it helps!
In one of my apps, I did this by having two RadioButon ArrayLists, one for each group. In onCreate() after the layout is inflated, the RadioButtons are added to each group as described in this answer.
Then, by checking for which ArrayList contains the RadioButton, the required logic can be implemented.
i described full example of your question please apply my solution
public class MyClass extends Activity implements RadioGroup.OnCheckedChangeListener
{
RadioGroup rg1,rg2,rg3;
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.main);
rg1=(RadioGroup)findViewById(R.id.rg1);
rg2=(RadioGroup)findViewById(R.id.rg2);
rg3=(RadioGroup)findViewById(R.id.rg3);
rg1.setOnCheckedChangeListener(this);
rg2.setOnCheckedChangeListener(this);
rg3.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(radioGroup==rg1)
{
//First RadioGroup Clicked
RadioButton radio=(RadioButton)findViewById(i);
Toast.makeText(this,radio.getText().toString(),Toast.LENGTH_SHORT).show();
}
if(radioGroup==rg2)
{
//Second RadioGroup Clicked
RadioButton radio=(RadioButton)findViewById(i);
Toast.makeText(this,radio.getText().toString(),Toast.LENGTH_SHORT).show();
}
if(radioGroup==rg3)
{
//Third RadioGroup Clicked
RadioButton radio=(RadioButton)findViewById(i);
Toast.makeText(this,radio.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
}

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);

Can a RadioGroup span more than one layout?

I have sucessfully made and used RadioGroup's before in xml, but each time there was a set of radio buttons in succession, all within the same LinearLayout. Now I wish to define a set of radio buttons to be part of a group, but they are not in the same layout. My start and end code for the group is:
START:
<RadioGroup android:id="#+id/radioGroup1" >
END:
</RadioGroup>
If I place this around each button individually, then it compiles, but the buttons don't act as radio buttons (i.e. activating one did not de-activate the others). If I try to place the "start" before any of the buttons and put the "end" after the last of them, then I get compilation errors.
Store the RadioButtons in an array. Instead of grouping them in a RadioGroup, you have to enable/disable them yourself. (un-tested so no copying/pasting )
declare these variables
private ArrayList<RadioButton> mGroup = new ArrayList<RadioGroup>();
private CompoundButton.OnCheckedChangeListener mListener = new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
for(RadioButton btn : mGroup)
btn.setChecked(false);
buttonView.setChecked(true);
}
}
Somewhere in your activity:
mGroup.add(your radiobuttons); // e.g. (RadioButton)findViewById(R.id.radio_button1);
mGroup.add(another radiobutton);
for(RadioButton btn : mGroup)
btn.setOnCheckedChangeListener(mListener)
Maybe you have to invalidate your Buttons after checking/unchecking them, to cause a redraw
Unfortunately the SDK does not directly support doing this, you would need to create a custom "group" to manager the buttons.
All the mutual exclusion logic for each RadioButton is managed by RadioGroup, so all the buttons have to be added to the same group. RadioGroup is a subclass of LinearLayout, so this inherently means they also need to all be in the same layout. RadioGroup manages each button's checked status by iterating through its children, which is why the two can't be divorced.
Here is a link to the RadioGroup source code as a starting point, you could create a custom Manager that uses the same logic here to manage the status of which button is checked in order to separate them from their layout status. RadioGroup basically just registers itself as an OnCheckedChangeListener for each child that is a RadioButton and then controls the check status of all the buttons based on user events.
HTH
Here's a refined and tested version of the first part of Entreco's code:
final ArrayList<RadioButton> mGroup = new ArrayList<RadioButton>();
CompoundButton.OnCheckedChangeListener mListener = new CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
for(RadioButton btn : mGroup) {
if (buttonView.getId() != btn.getId() && isChecked) {
btn.setChecked(false);
}
}
}
};
It will uncheck only the other buttons and only if the state of the clicked button changed from unchecked to checked.
#Entreco answer can cause recursive call to onCheckedChanged which is fixed by #Twilite answer.
But #Twilite answer also has a problem and that's the id of views without explicit id may not be unique. If that happen, you may see either multiple selected radio buttons or none of them being checked. So, it's safer to either set a unique id or a unique tag for each one:
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
for (RadioButton btn : mGroup)
if (!btn.getTag().equals(compoundButton.getTag()))
btn.setChecked(false);
}
}

Categories

Resources