我希望循环遍历一项 Activity 中的所有切换按钮并执行两件事之一。在一种情况下我想设置它们的值,在另一种情况下我想读取它们的值。最简单的方法是循环遍历子项,尝试检查它们的切换按钮类型,然后执行前面提到的任务?
我会使用这样的东西吗?
for (int i = 0; i < rootView.getChildCount(); i++)
if (Widget_Tag != null){
View Current_Widget = (View) rootView.getChildAt(i);
String Widget_Tag = (String) Current_Widget.getTag();
if (Widget_Tag.equals("MyToggleButton")) {
//do something
}
}
******更新******
工作代码如下(感谢回答),我嵌套了另一个 for 循环来为我的 ToggleButtons 挖掘一个子层:
ViewGroup rootView = (ViewGroup) findViewById(R.id.LayoutHere);
for (int i = 0; i < rootView.getChildCount(); i++) {
ViewGroup nextLayout = (ViewGroup) rootView.getChildAt(i);
for (int i2 = 0; i2 < nextLayout.getChildCount(); i2++) {
View Current_Widget = nextLayout.getChildAt(i2);
if(Current_Widget instanceof ToggleButton)
{
//Do Something
}
}
}
最佳答案
如果您使用String
“MyToggleButton”标记您的ToggleButton
,则您正在做的事情将会起作用:
ToggleButton button = getSomeToggleButton();
button.setTag("MyToggleButton");
如果您之前没有做过类似上述的事情,那么您的代码 fragment 将不起作用。您可以对每个 View
进行 instanceof
检查。
if(Current_Widget instanceof ToggleButton) {// or instanceof MyToggleButton if that is a class of yours...
//do something
}
关于java - 循环遍历 Activity 中的切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6165202/