アプリにラジオ ボタンの長いリストがあります。
テキストに文字列「test」が含まれていないすべてのボタンを削除するにはどうすればよいですか?
これを自動化できます:
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 の呼び出し後、イテレータのコードとビューグループの状態をテストしませんでした。コンソールで確認してお知らせください。
それらを 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);
}