how to remove radio button items programmatically - android

In xml layout I have RadioGroup, Button1, Button2. When user clicks on button1, several radio buttons are programmatically created in RadioGroup (total amount of radio buttons may differ (pocet = count of radio buttons to be created).
final RadioButton[] rb = new RadioButton[pocet];
RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);
radiobuttonCount++;
for(int i=0; i<pocet; i++){
rb[i] = new RadioButton(this);
rb[i].setText("Radio Button " + radiobuttonCount);
rb[i].setId(radiobuttonCount+i);
rb[i].setBackgroundResource(R.drawable.button_green);
rg.addView(rb[i]);
}
What I try to do is this: When user selects xy item from RadioGroup, I'll pass selected value to textview and remove all radioButtons.
For deleting purpose I use:
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
boolean isChecked = checkedRadioButton.isChecked();
if (isChecked)
{
RadioGroup rg = (RadioGroup) findViewById(R.id.MyRadioGroup);
for (int i=0; i< rg.getChildCount(); i++){
rg.removeViewAt(i);
}
}
Problem is that this sometimes works well, but sometimes first radio button remains undeleted.
P.S.
Later I want to add button2 that will feed radiogroup with different items and different radio buttons amount. That's why I need to remove all radio buttons after user does selection.

Its really easy, you just do this:
rg.removeAllViews();
because i worked with the for loop but it didn't remove all the RadioButtons.
have fun :)

My first guess is that this portion of code is bad:
for (int i=0; i< rg.getChildCount(); i++){
rg.removeViewAt(i);
}
you can't run over one view's children while removing child at the same time
(rg.getChildCount() will change during the run)

Related

How to get the selected index of dynamically added radio buttons

I had added radio buttons dynamically like below.
for (int i = 0; i< typeArrayList.size(); i++) {
radioButtons[i] = new RadioButton(MainActivity.this);
radioButtons[i].setId(i);
radioButtons[i].setText(typeArrayList.get(i).toString());
if(i==0) {
radioButtons[i].setChecked(true);
}
typeLayout.addView( radioButtons[i]);
}
I have a button when clicked calls a method to which the selected item (text) of the dynamically added radio buttons should be passed . How can I get the selected radio button text for the dynamically added radio buttons?
Its very important to set your radio button id when adding buttons to a radio group.
RadioButton rb = new RadioButton(context);
rb.setText(option);
rb.setId(rb.hashCode());
radioGroup.addView(rb);
radioGroup.setOnCheckedChangeListener(mCheckedListner);
Now in your click listener check for the unique id.
private RadioGroup.OnCheckedChangeListener mCheckedListner = new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
JSONArray actionArray = new JSONArray();
if(group.findViewById(checkedId)!=null) {
RadioButton rb = ((RadioButton) group.findViewById(checkedId)).getText();
//Your Code here
}
}
}
};
You have stored all RadioButtons that you create dynamically in a radioButtons array.
So if you want to know which radiobutton is selected you can loop all this array and check each RadioButton
for (int i = 0; i< radioButtons.size(); i++) {
if(radioButtons[i].isChecked()){
// selected radio button is here
String text = radioButtons[i].getText();
}
}
First you have to get all childs of your view. Then check if this view is RadioButton. And at last check which button is checked.
int childcount = typeLayout.getChildCount();
for (int i=0; i < childcount; i++){
View view = typeLayout.getChildAt(i);
if (view instanceof RadioButton) {
if(((RadioButton)view).isChecked()) {
RadioButton yourCheckedRadioButton = (RadioButton) typeLayout.getChildAt(i); // this is your checked RadioButton
}
}
}
#Komali Shirumavilla
Add those dynamic radio buttons to radio group
so add following lines in your code
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
for (int i = 0; i< typeArrayList.size(); i++) {
radioButtons[i] = new RadioButton(MainActivity.this);
radioButtons[i].setId(i);
radioButtons[i].setText(typeArrayList.get(i).toString());
if(i==0) {
radioButtons[i].setChecked(true);
}
rg.addView(radioButtons[i]); // add dynamic radio buttons to radio group
}
typeLayout.addView(rg); // add radio group to view
Now set setOnCheckedChangeListener on the RadioGroup
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId) {
RadioButton btn = (RadioButton)findViewById(checkedId);
Log.d("Your selected radio button id",btn.getText());
}
}
});
This can be simply achieved using tags.
While adding the RadioButton set a tag that particular object. In your case, set the tag to be the text of the radio button,
radioButtons[i].setTag(typeArrayList.get(i).toString());
This way all your radio buttons will have the text associated to them as a tag.
Now whenever a particular radio button is selected, just get the tag which will give you the text associated with it.
String text = (String) selectedRadioButton.getTag();
Hope it helps.

How to get all of unchecked radio buttons in android

I have 16 Radio Group in my layout and i have 40 Radio Button . I want to get which Radio Button is unchecked in Radio Groups. I want to know how can i know is there any unchecked Radio Button in my layout thanks
You should probably group all of your buttons like so:
RadioGroup rg = (RadioGroup) findViewById(R.id.my_radio_group);
List<RadioButton> radioButtonsList = new ArrayList<>();
for(int i = 0; i < rg.getChildCount(); ++i) {
RadioButton b = rg.getChildAt(i);
if(b.isChecked()) radioButtonsList.add(b);
}
Do it for all of your groups and you'll have all your unchecked buttons in a list.
Also you can use:
int checkedRadioButtonId = rg.getCheckedRadioButtonId()
to get only checked button's id.
ArrayList<RadioGroup> radioGroupList = new ArrayList<RadioGroup>();
RadioGroup group1 = (RadioGroup)findViewById(...);
RadioGroup group2 = (RadioGroup)findViewById(...);
.
.
RadioGroup group16 = (RadioGroup)findViewById(...);
radioGroupList.add(group1);
radioGroupList.add(group2);
.
.
radioGroupList.add(group16);
and later you can check which is checked or not with this
for(RadioGroup radioButtonGroup:RadioGroupList){
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
}
or if it's the RadioButtons you are interested in then add them in an ArrayList the same way and loop in that list like this
for(RadioButton radioButton:radioButtonList){
boolean isChecked = radioButton.isChecked();
}
You can check the state of radio buttons by using the isChecked() method.
This question has already been answered here:
How to check if "Radiobutton" is checked?

android: radio buttons inside radio buttons

I am quite new to Android and this is my first application, so please correct if my question is not clear and I will gladly add more information about what I am trying to achieve.
I have a radio group built dynamically. Inside this radio group I would like to have another radio group, depending on the radio button chosen from the first group.
So, let's say I have an array list of items and for each item I have some sizes available (i.e: XS, S, L). If I check the radio button "XS", I would like to have another radio group with the available colors for the selected size, XS.
The way I have built this is by creating a radio group and it's radio buttons dynamically. Inside the method onCheckedChanged(), I am calling the method createRadioButtonsForAvailableColors(). This one creates the radio buttons with the necessary colors for the checked size, but once I check another size in the upper radio group, the new colors available for this size are added to the colors shown for the size selected before.
Thank you.
Here is my on create method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_product_details);
sizesList = getSizes(getIDFromPreviousActivity());
createRadioButtonsForAvailableSizes(sizesList);
}
Here is my creation for the radio group containing the radio buttons with the available sizes:
// creates the radio buttons with the available sizes
public void createRadioButtonsForAvailableSizes(ArrayList<String> sizeList) {
productDetailsLayout = (LinearLayout) findViewById(R.id.productDetailsLayout);
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.HORIZONTAL);
int n = sizeList.size();
final RadioButton[] rb = new RadioButton[n];
for(int i=0; i< sizeList.size(); i++) {
colorList = getColors(getIDFromPreviousActivity(),sizeList.get(i));
rg.setOrientation(RadioGroup.HORIZONTAL);
rb[i] = new RadioButton(this);
rg.addView(rb[i]);
rb[i].setText(sizesList.get(i).toString());
rb[i].setId(getIDForRadioButton(sizesList.get(i).toString()));
rb[i].setButtonDrawable(R.drawable.radiobuttonunchecked);
rb[i].setOnCheckedChangeListener(this);
}
productDetailsLayout.addView(rg);
productDetailsLayout.setPadding(50, 50, 50, 50);
}
Here is the creation of the colors (same as for the sizes):
// create radio buttons for available colors
public void createRadioButtonsForAvailableColors(ArrayList<String> colorList) {
Log.d("createRadioButtonsForAvailableColors","");
productDetailsLayout = (LinearLayout) findViewById(R.id.productDetailsLayout);
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.HORIZONTAL);
int n = colorList.size();
final RadioButton[] rb = new RadioButton[n];
for(int i=0; i< colorList.size(); i++) {
Log.d("color"+i,colorList.get(i));
rg.setOrientation(RadioGroup.HORIZONTAL);
rb[i] = new RadioButton(this);
rg.addView(rb[i]);
rb[i].setText(colorList.get(i).toString());
rb[i].setId(getIDForRadioButton(colorList.get(i).toString()));
rb[i].setButtonDrawable(R.drawable.radiobuttonunchecked);
rb[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton button, boolean isChecked) {
button.setButtonDrawable(isChecked ? R.drawable.radiobuttonchecked : R.drawable.radiobuttonunchecked);
}
});
}
productDetailsLayout.addView(rg);
productDetailsLayout.setPadding(50, 50, 50, 50);
}
Here is my onCheckedChange method:
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
button.setButtonDrawable(isChecked ? R.drawable.radiobuttonchecked : R.drawable.radiobuttonunchecked);
String text = button.getText().toString();
int productID = getIDFromPreviousActivity();
ArrayList<String> colorList = getColors(productID, text);
createRadioButtonsForAvailableColors(colorList);
}
The inner group is created right, but upon checking one size in the first group, it builds the subgroup radio buttons normally. If I click one size, it shows the available colors. But, on changing the size checked, the buttons showing the colors of the now selected size are added to the buttons shown before for the previous size selected. How can I cancel the inner buttons created when I selected first time the size and show only the available colors for the currently selected size?
I think this is maybe not the right approach to build it. So, I have 2 questions:
Usually, what would be the best way to do this? Since my inner radio group depends on the radio button chosen from the first group, I assume the creation of the inner group should be called inside the onCheckedChange() method. Should I start another activity from here or can I do it all in one activity?
If my approach is correct, can you please tell me how to delete the inner radio buttons created, in case the radio button from the main group is changed?
Thank you
So, if I understood this, the problem comes when you change the value of the sizes radio button, meaning the colors don't disappear.
Well, Java is all about a lot of boilerplating, and there's not pretty much to say (I'd probably go for a similar way).
You could add this inside the createRadioButtonsForAvailableColors method, just before you start adding content:
productDetailsLayout.removeViews(0, productDetailsLayout.getChildCount());
RemoveViews will remove any amount of child views starting from a position (hence I amb passing it 0 and the total of children).

RadioGroup.clearCheck() not working in case of dynamically created radio buttons

In my app,i am creating radio buttons dynamically and want to uncheck all other radio buttons when one of them is checked.For this purpose,i am using RadioGroup.clearCheck() but it is not working at all.This is the code:
for (int i=0; i<files.length; i++)
{
rbi = new RadioButton(context);
rb1 = new RadioGroup(context);
rb1.addView(rbi);
nameOfFile = files[i].getName();
rbi.setText(nameOfFile);
ll.addView(rb1);
rbi.setOnClickListener(
new RadioButton.OnClickListener()
{
#Override
public void onClick(View v)
{
rb1.clearCheck();
rbi.setChecked(true);
}
Please help me.Even the alternate solutions for achieving the goal will be welcomed.Thanks in advance.
You create a lot of RadioGroups with just 1 RadioButton inside. That is probably not what you want. A RadioGroup needs to contain several RadioButtons so you can select an active button inside the list. See code below
// create 1 RadioGroup, add it to the layout
RadioGroup rg = new RadioGroup(context);
ll.addView(rg);
// add several RadioButtons to the RadioGroup
for (int i=0; i < files.length; i++) {
String nameOfFile = files[i].getName();
RadioButton rb = new RadioButton(context);
rb.setId(i); // assign an id
rb.setText(nameOfFile);
rg.addView(rb); // add to group
}
// do something when user checks a button
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// user selected files[checkedId].getName();
}
});
Did you try (with System.out.println("test");) or something, if it even gets into the clearing part? Would test that first.
This is what zapl means
rb1.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup rb1,
int checkedId) {
Log.v("Selected", "New radio item selected: " + checkedId);
}
});
if that works, then you can try this:
if (rbi.isChecked()){
rb1.clearCheck();
rbi.setChecked(true);
}

How to add radio buttons to radio group

I have a TableLayout and in the third column of every row I want to place a radio group.
I build the RadioButtons like this:
rg = (RadioGroup) findViewById(R.id.radioGroup1);
for (int k = 0; k < size; k++) {
rb[k] = new RadioButton(context);
rg.addView(rb[k]);
}
However this cause my app to crash, any ideas?
You are building a primitive array with the length of megethos, but your loop uses the length size. If megethos and size are different values this can cause many different types of errors... But all of this redundant since a RadioGroup keeps this array up to date for you.
I would try something like this:
RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton button;
for(int i = 0; i < 3; i++) {
button = new RadioButton(this);
button.setText("Button " + i);
group.addView(button);
}
And when you want to reference a button at index:
group.getChildAt(index);
Also please always post your logcat errors, it tells us exactly what went wrong and where to look. Otherwise we have to guess like this.
Update
The error is because you are trying to add the same button to two different layouts:
tr[k].addView(rb[k]);
rg.addView(rb[k]);
a view can only have one parent. As far as I know you cannot break a RadioGroup apart into multiple views without a lot of customization first. However a ListView already has the built-in feature setChoiceMode() that behaves like a RadioGroup:
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, list);
ListView listView = (ListView) findViewById(R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setAdapter(adapter);
You can easily adapt simple_list_item_checked to display the SSID and signal strength. Hope that helps. (If you wait long enough imran khan might cut & paste my answer with graphical change, then claim it as his own again.)
I have created one demo app in which I have added Radio buttons dynamically and also handled click events.
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup2;
ArrayList<String> buttonNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup2 = (RadioGroup) findViewById(R.id.radioGroup2);
buttonNames = new ArrayList<>();
buttonNames.add("No Tip");
buttonNames.add("10%");
buttonNames.add("20%");
buttonNames.add("30%");
radioGroup2.setWeightSum(Float.parseFloat(buttonNames.size() + ""));
radioGroup2.setBackgroundColor(Color.BLUE);
for (int i = 0; i < buttonNames.size(); ++i) {
RadioButton radioButton = new RadioButton(this);
radioButton.setId(i);
RadioGroup.LayoutParams childParam1 = new RadioGroup.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f);
childParam1.setMarginEnd(2);
radioButton.setGravity(Gravity.CENTER);
radioButton.setLayoutParams(childParam1);
radioButton.setBackground(null);
radioButton.setText(buttonNames.get(i));
radioButton.setTextColor(Color.BLUE);
radioButton.setBackgroundColor(Color.WHITE);
radioButton.setButtonDrawable(null);
if (buttonNames.get(i).equals("20%")) {
radioButton.setChecked(true);
radioButton.setBackgroundColor(Color.BLUE);
radioButton.setTextColor(Color.WHITE);
}
radioGroup2.addView(radioButton, childParam1);
}
radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i1) {
RadioButton button = null;
for (int i = 0; i < buttonNames.size(); ++i) {
if (i1 == i) {
button = (RadioButton) findViewById(i1);
button.setChecked(true);
button.setBackgroundColor(Color.BLUE);
button.setTextColor(Color.WHITE);
Toast.makeText(getApplicationContext(), button.getText() + " checked", Toast.LENGTH_SHORT).show();
} else {
button = (RadioButton) findViewById(i);
button.setChecked(false);
button.setBackgroundColor(Color.WHITE);
button.setTextColor(Color.BLUE);
}
}
}
});
}
}

Categories

Resources