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>
Related
I am trying to create a button for each year since the person started using my app. So in my xml document I have
<HorizontalScrollView
android:id="#+id/yearScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/currentYear"
android:tag="01"
android:text="2015"
android:paddingLeft="8.0dip"
android:paddingRight="8.0dip"
android:height="24dp"
android:textSize="18sp"
android:textColor="#333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
>
</Button>
</LinearLayout>
</HorizontalScrollView>
Then I have the following code
private List<Button> yearButtons;
private static final int[] YEAR_BUTTON_IDS = {
R.id.currentYear,
};
Then I must find out what year it is and overwrite my current button
int firstYear = Integer.parseInt(year);
yearButtons.get(0).setText(String.valueOf(CurrentYear));
then in my init class I substantiate the buttons, I understand I do not need a loop for only 1 button but leaving it like this for consistency with how the months buttons work
for(int id : YEAR_BUTTON_IDS) {
Button button = (Button)findViewById(id);
button.setOnClickListener(this);
yearButtons.add(button);
}
Then I have some logic to find out the first year they started called yearsOfTransactions
Then I have the following loop where I try create the buttons
for (int i =0; i< yearsOfTransactions; i++){
int yearToAdd = CurrentYear-i-1;
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
}
However this is not working..
Thanks for any help
I am making slight modification in your code :
<HorizontalScrollView
android:id="#+id/yearScrollView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:layout_gravity="center">
<LinearLayout
android:id="#+id/button_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/currentYear"
android:tag="01"
android:text="2015"
android:paddingLeft="8.0dip"
android:paddingRight="8.0dip"
android:height="24dp"
android:textSize="18sp"
android:textColor="#333333"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
>
</Button>
</LinearLayout>
</HorizontalScrollView>
Now make an array of years to add (in onCreate())
int[] yearToAdd = {2000, 2001, 2002, 2003};
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.button_parent);
for (int i =0; i< yearToAdd.lenght; i++){
int yearToAdd = yearToAdd[i];
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
yearButtons.setOnClickListener(this);
parentLayout.addView(myButton);
}
Let me know in case of more clearation you need, hope it will help :)
you have to add button to a linear layout.
This is a function i use to add dynamic buttons in a linear layout.
public Button createButton(String label) {
Button button = new Button(mContext);
button.setText(label);
mDynamicLayout.addView(button, mLayoutParam);
return button;
}
You should add every button you create to the LinearLayout. First set and id in xml to LinearLayout. Find the view in your class and, finally, add the buttons.
LinearLayout container = findViewById(R.id.container);
//...
for (int i =0; i< yearsOfTransactions; i++){
int yearToAdd = CurrentYear-i-1;
Button myButton = new Button(this);
myButton.setText(String.valueOf(yearToAdd));
yearButtons.add(myButton);
// you missed that
container.addView(myButton);
}
please try this inside your for loop
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);
//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);
//add button to the layout
layout.addView(btnTag);
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>
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>
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)
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.