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"?
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"?
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.
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.
.equals() for string comparison -- you cannot use == or !=.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); }