0

I have a long list of radio buttons in my app.

How can I remove all buttons whose text does not contain the string "test"?

2
  • How do you create these buttons? dynamically or via xml layout? Commented Sep 30, 2013 at 0:04
  • @jeraldov I generate them in my xml layout file Commented Sep 30, 2013 at 0:06

3 Answers 3

1

You could automate this:

ViewGroup vg= (ViewGroup) findViewById(R.id.your_layout); int iter=0; while(iter<vg.getChildCount()){ boolean found=false; View rb=vg.getChildAt(iter); if(rb instanceof RadioButton){ if(rb.getText().toString().contains(my_string)){//found a pattern vg.removeView(rb);//remove RadioButton found=true; } } if(!found) ++iter;//iterate on the views of the group if the tested view is not a RadioButton; else continue to remove } 

The code above doesn't deal with viewgroups inside another viewgroup (e.g. LinearLayout inside another one). I didn't test the code for the iterator and the state of the viewgroup after the call to removeView; you could check it in a console and let us know.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for this answer, after a bit of tweaking it worked perfectly!
1

Example for one button:

Button buttonOne = (Button) findViewById(R.id.buttonOne); removeButtons(); public void removeButtons() { if (buttonOne.getText().toString() != "test") { buttonOne.setVisibility(GONE); } } 

Switch it up if you have an array.

1 Comment

You have to use .equals() for string comparison -- you cannot use == or !=.
1

If you have them together in a list like List it is very simple.

List<RadioButton> testButtons = new ArrayList<RadioButton>(); for (RadioButton button: radioButtonList) { if (button.getText().toString().contains("test")) { testButtons.add(button); } } // assuming that they all have the same parent view View parentView = findViewById(R.id.parentView); for (RadioButton testButton: testButtons ) { parentView.removeView(button) // or as Evan B suggest, which is even simpler (though then it is not 'removed' from the view in the litteral sense testButton.setVisibility(GONE); } 

1 Comment

thanks for you answer, but I ended up using a version of Eudhan's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.