我的应用中有一长串单选按钮。
如何删除文本中不包含字符串“test”的所有按钮?
答案 0 :(得分:1)
如果你把它们放在像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);
}
答案 1 :(得分:1)
一个按钮的示例:
Button buttonOne = (Button) findViewById(R.id.buttonOne);
removeButtons();
public void removeButtons() {
if (buttonOne.getText().toString() != "test") {
buttonOne.setVisibility(GONE);
}
}
如果你有阵列,请将其切换。
答案 2 :(得分:1)
你可以自动执行此操作:
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之后,我没有测试迭代器的代码和viewgroup的状态;你可以在控制台中查看它并告诉我们。