Set selected index of an Android RadioGroup - android

Is there a way to set the selected index of a RadioGroup in android, other than looping through the child radiobuttons and selecting checking the radio button at the selected index?
Note: I am populating the Radio Button Group at run time.

If your radio group is defined in a layout xml file, each button can be assigned an id. Then you just check a button like this
radioGroup.check(R.id.myButtonId);
If you created your radio group programmatically (I'm not even sure how you do this...), you might want to consider creating a special layout xml file just for the radio group so that you can assign R.id.* ids to the buttons.
Please see the answer below if you are, in fact, looking to set the radio button group by index, see the answer below.
((RadioButton)radioGroup.getChildAt(index)).setChecked(true);

Question said "set selected INDEX", here's how to set it by index:
((RadioButton)radioGroup.getChildAt(index)).setChecked(true);
........
Additional info: It seems that Google wants you to use id instead of index, because using id is more bug proof. For example, if you have another UI element in your RadioGroup, or if another developer re-orders the RadioButtons, the indices might change and not be what you expected. But if you're the only developer, this is totally fine.

you can do findViewById from the radio group .
((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);`

Siavash's answer is correct:
((RadioButton)radioGroup.getChildAt(index)).setChecked(true);
But be aware that a radioGroup can contain views other than radioButtons -- like this example that includes a faint line under each choice.
<RadioGroup
android:id="#+id/radioKb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/kb1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Onscreen - ABC" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
<RadioButton
android:id="#+id/kb2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Onscreen - Qwerty" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
<RadioButton
android:id="#+id/kb3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Standard softkey" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
<RadioButton
android:id="#+id/kb4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:button="#null"
android:drawableRight="#android:drawable/btn_radio"
android:text="Physical keyboard" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#33000000" />
</RadioGroup>
In this case using an index of 1, for example, would generate an error. The item at index 1 is the first separator line -- not a radioButton. The radioButtons in this example are at indexes 0, 2, 4, 6.

This Worked For me, I created radio button dynamically by
private void createRadioButton() {
RadioButton[] rb = new RadioButton[5];
RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
1.0f);
radioGroup.setOrientation(RadioGroup.HORIZONTAL);
for (int ID = 0; ID < 5; ID++) {
rb[ID] = new RadioButton(this);
rb[ID].setLayoutParams(layoutParams);
rb[ID].setText("Button_Text");
radioGroup.addView(rb[ID]); //the RadioButtons are added to the radioGroup instead of the layout
}
}
Now Check a button using,
int radio_button_Id = radioGroup.getChildAt(index).getId();
radioGroup.check( radio_button_Id );

Inside onBindViewHolder set the tag to Button Group
#Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
...
holder.ButtonGroup.setTag(position);
}
and in the ViewHolder
ButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
...
int id = radioGroup.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) radioGroup.findViewById(id);
int clickedPos = (Integer) radioGroup.getTag();
packageModelList.get(clickedPos).getPoll_quest()
}

Using Kotlin you can make it by
(radio_group_id.getChildAt(index) as RadioButton).isChecked = true
or
radio_group_id.check(R.id.radio_button_id)

Related

Android using if statement on textview and imagebutton

Hello guys i am making simple game that can take point if i click right button.
so there is 5 imagebutton and 1 textview. textview will generate random number 1-5 . and those 5 imagebuttons has 5 different id , so my point is if textview generates 1 number how can i check it its right button using if statement.
if ( textview(current generated number ) == imagebutton(id) ) {
counter++)
something like this can you help me guys? example code would be nice :D
Set the tag value for the buttons
either from xml set Tag attribute
Tag = "1"
or
btn.setTag("1");
Add the buttons corresponding value to its tag and then compare it with tags value
in onClick method you get id of button clicked
Button btn = (Button) findViewById(id);
string valu = btn.getTag();
Now compare the textView value with this tag value.
string txt = textView.getText();
if(txt.equals(valu))
{
// do what you want
}
You could store the button resource IDs an array of int. Then in a common click handler, you could test whether the button clicked was the same as the one randomly selected. Here's a simplistic, minimal example. It assumes you've set and displayed the random number before you get the button clicks.
In your class, define these fields:
private int myButtons[] = null;
private int randomNumber = 0;
In onCreate(), add the following:
myButtons = new int[] {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4};
Add the method:
public btnClick(View v) {
if (findViewById(myButtons[randomNumber]) == v)
Log.i(TAG, "Correct!");
else
Log.i(TAG, "Incorrect!");
}
Then in your layout XML, define the buttons with your click handler:
<Button
android:id="#+id/btn0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn0" />
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn1" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn2" />
<Button
android:id="#+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn3" />
<Button
android:id="#+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="#string/btn4" />

Set default checked Radio Button

I'm creating a RadioGroup with RadioButtons dynamically and need to have one radio button checked by default.
I've done this by using both radioButton.setChecked(true) and radioButton.toggle();
The problem I have is that when I at runtime select another radio button the first one stays checked so I end up with two checked radio buttons in the radio group.
Has anyone had this problem and know how to solve it?
private RadioButton addRadioButton(String type, String price){
RadioButton radio = new RadioButton(Order.this);
radio.setText(type + " (" + Utils.formatCurrency(price) + ")");
radio.setTextAppearance(Order.this, R.style.portalCellTextStyle);
radio.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
radio.setTag(price);
if(type.toLowerCase().equals("m"))
radio.toggle();
return radio;
}
I know I'm late but for those who search for the answer like me this can be useful.
When you add RadioButton to a RadioGroup, you must set the button checked after adding it to the parent like:
RadioGroup radioGroup = new RadioGroup(getContext())
RadioButton radioButton = new RadioButton(getContext());
radioButton.setText("text");
mRadioGroup.addView(radioButton);
radioButton.setChecked(true);
If the view is checked before adding it to the parent, it will be impossible to uncheck it.
You can do this simply:
JAVA:
radiogroup =(RadioGroup)findViewById(R.id.radiogroup);
radiobutton1 =(RadioButton)findViewById(R.id.radiobutton1);
radiobutton2 =(RadioButton)findViewById(R.id.radiobutton2);
if(your first assessment){
radiobutton1.setChecked(true);
}else{
radiobutton2.setChecked(true);
}
XML:
<RadioGroup
android:id="#+id/radiogroup"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/radiobutton1"
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RadioButton
android:id="#+id/radiobutton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RadioGroup>
Simple, at first time load the screen check the position of In Getview method and then apply condition:
if (position == 0) {
holder.act_delivery_rbtn.setChecked(true);
}
If you are only using one radio box for checking on and off, maybe you should use checkbox or toggle button instead.
http://developer.android.com/resources/tutorials/views/hello-formstuff.html
Scroll down and see checkbox and toggle button.
When using radios you usually have more than one and choose between them. Like easy, medium, hard.
Replace
radio.toggle();
with
radio.setChecked(true);
Just make checked = "true" in your code
you should check it in radio group...
radiogroup.check(IdOfYourButton)
use the clearCheck () function to clear the already checked buttons.I hope this solves your problem.
Turned out to be because I called the checked() method on the radio group straight after setting the OnCheckedChangeListener() causing it to be called immediately and throw a NPE for some reason.
Moved the checked() method call to just before the OnCheckedChangeListener() and it works now.
radios.check(2);
radios.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
});
private RadioButton addRadioButton(String type, String price){
RadioButton radio = new RadioButton(Order.this);
radio.setText(type + " (" + Utils.formatCurrency(price) + ")");
radio.setTextAppearance(Order.this, R.style.portalCellTextStyle);
radio.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
radio.setTag(price);
if(type.toLowerCase().equals("m"))
radio.setId(2);
return radio;
}
in Xml add android:checkedButton="#+id/storeRB" to RadioGroup
<RadioGroup
android:id="#+id/storeTypeRG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkedButton="#+id/storeRB"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="#+id/text2"
app:layout_constraintStart_toEndOf="#+id/text2"
app:layout_constraintTop_toTopOf="#+id/text2">
<RadioButton
android:id="#+id/storeRB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:button="#drawable/radio_button_bg"
android:paddingStart="8dp"
android:text="#string/store_str"
app:layout_constraintBottom_toBottomOf="#+id/text2"
app:layout_constraintStart_toEndOf="#+id/text2"
app:layout_constraintTop_toTopOf="#+id/text2" />
<RadioButton
android:id="#+id/hyperRB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:button="#drawable/radio_button_bg"
android:paddingStart="8dp"
android:text="#string/hyper_str"
app:layout_constraintBottom_toBottomOf="#+id/text2"
app:layout_constraintStart_toEndOf="#+id/storeRB"
app:layout_constraintTop_toTopOf="#+id/text2" />
<RadioButton
android:id="#+id/restaurantRB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:button="#drawable/radio_button_bg"
android:paddingStart="8dp"
android:text="#string/restaurant_str"
app:layout_constraintBottom_toBottomOf="#+id/text2"
app:layout_constraintStart_toEndOf="#+id/hyperRB"
app:layout_constraintTop_toTopOf="#+id/text2" />
</RadioGroup>

Radio buttons simultaneously checked

I'm creating a radio group with radio buttons (from an enumeration) at runtime with the following code.
RadioGroup radioGroup = new RadioGroup(this);
List<LocationTypeEnum> warningTypes = preferences.getWarningTypes();
for (LocationTypeEnum enumElement : warningTypes) {
RadioButton radio = new RadioButton(this);
radio.setText(enumElement.toString());
//Check one specific radio by default
radio.setChecked(enumElement.intValue == userDefinedLocation.getType().intValue);
radioGroup.addView(radio, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
When it comes to screen and I try to change the radio, both options remain checked:
What's going wrong?
Found the answer. You must add the RadioButton to the RadioGroup before setting it to checked, or else the radio group gets lost. Following, the correct code.
RadioGroup radioGroup = new RadioGroup(this);
List<LocationTypeEnum> warningTypes = preferences.getWarningTypes();
for (LocationTypeEnum enumElement : warningTypes) {
RadioButton radio = new RadioButton(this);
radio.setText(enumElement.toString());
//First, add the radio to the group
radioGroup.addView(radio, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
//Only after that you can check it.
radio.setChecked(enumElement.intValue == userDefinedLocation.getType().intValue);
}
Sounds like a bug, to me. Credits to http://code.google.com/p/android/issues/detail?id=1772
Don't know how to comment to ask you to post your layout .xml file. Make sure that you also group them in your xml file like below:
<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>

Add radio button dynamically in an Android app

I need to add radio button dynamically. A radio button may be 3, 4, 5 or 6 and it would be added horizontally and one row contains maximum 3 radio button.
If there are more than 3 then it would come below of above row of radio button as in grid view. My code for radio button are below but it display all radio button in a single row, means it's hiding the radiobutton.
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" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Your Favorite Actress" >
</TextView>
<RadioGroup
android:id="#+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</RadioGroup>
<Button
android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" >
</Button>
</LinearLayout>
And Java class is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayRadioButton();
}
public void DisplayRadioButton() {
for(int i=0;i<10;i++) {
RadioGroup radiogroup = (RadioGroup)findViewById(R.id.RadioGroup01);
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(i);
rdbtn.setText(text[i]);
radiogroup.addView(rdbtn);
}
}
please try in the following way:
1)in your xml remove the RadioGroup. create it by dynamically
RadioGroup radiogroup[];
RadioButton rdbtn[];
LinearLayout linear[];
radiogroup = new RadioGroup[9/3];
rdbtn = new RadioButton[9];
linear = new LinearLayout[9/3];
......
int count = 0; // integer flag
for(int i=0;i<9;i++){
if the value of i is equal to 3 multiple then increase count by 1
// sett linear[count]'s orientation is horizontal.
root_layout.addView(linear[count]);
radiogroup[count] = new RadioGroup(this);
linear[count].addView(radiogroup[count]); // add radio group to linear layout
add radio button to radio group.
rdbtn[i] = new RadioButton(this);
rdbtn[i].addView(radiogroup[count]);
}
i hope you get solved. be aware of array index out of bound exception.
your xml may look like:
<LinearLayout
android:id= rootlayout
..... // the child linearlayout
.. . radio group
... radio button
</LinearLayout>

Why cant I access the children of the radio group

I am trying to use this Android: How to get a radiogroup with togglebuttons? code of the given answer
but in
static final RadioGroup.OnCheckedChangeListener ToggleListener = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
for (int j = 0; j < radioGroup.getChildCount(); j++) {
final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
view.setChecked(view.getId() == i);
}
}
};
in line
final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
it always crashes. In Logcat I don't see any message.
I tried everything I could think of , but can't fid the problem -
Many thanks!
ps this is my xml for the radiogroup:
<RadioGroup android:id="#+id/radioGroup2" android:layout_width="150sp" android:layout_height="wrap_content"
android:paddingLeft = "10sp" android:layout_alignBottom="#+id/a2" >
<RadioButton android:layout_width="wrap_content" android:id="#+id/Settings_otherSettingsT2Yes" android:layout_height="wrap_content"
android:textColor="#000000" android:textSize="18sp"
android:text="#string/Settings_otherSettingsT2Yes" android:checked="false"></RadioButton>
<RadioButton android:layout_width="wrap_content" android:id="#+id/Settings_otherSettingsT2No" android:layout_height="wrap_content"
android:textColor="#000000" android:textSize="18sp"
android:text="#string/Settings_otherSettingsT2No"></RadioButton>
</RadioGroup>
...nothing special here
I checked the number of children by logging radioGroup.getChildCount() and it gives 2 as expected
In your code you cast RadioButtons to ToggleButton. This is likely to be the cause of your crashes. I don't understand why you can't find an exception in logcat.
However, you say you want to use code like in the link, but your XML is not close to the link. You use RadioButtons where the link uses ToggleButtons.
If you just want RadioButtons, then completely disregard that link.
If you want to use ToggleButtons then that link isn't the best way anyway. Adding ToggleButtons to a RadioGroup just confuses the intent of the code.

Categories

Resources