我的应用程序中有很长的单选按钮列表。
如何删除文本不包含字符串“test”的所有按钮?
如果您将它们放在像 List 这样的列表中,那将非常简单。
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);
}
一键示例:
Button buttonOne = (Button) findViewById(R.id.buttonOne);
removeButtons();
public void removeButtons() {
if (buttonOne.getText().toString() != "test") {
buttonOne.setVisibility(GONE);
}
}
如果您有阵列,请将其切换。
你可以自动化这个:
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
}
上面的代码不处理另一个视图组内的视图组(例如,另一个视图组内的 LinearLayout)。调用removeView后,我没有测试迭代器的代码和视图组的状态;您可以在控制台中检查它并告诉我们。