【发布时间】:2011-11-28 16:35:37
【问题描述】:
鉴于 android 中的新屏幕,我想遍历所有视图组和视图以发现所有按钮、文本字段、微调器等...这可能吗?
【问题讨论】:
-
查看 Romain Guy 的回答:stackoverflow.com/questions/2597230/…
鉴于 android 中的新屏幕,我想遍历所有视图组和视图以发现所有按钮、文本字段、微调器等...这可能吗?
【问题讨论】:
我获得了观看次数,然后将其用作 计数器调用 getChildAt(int index)
【讨论】:
这个问题可能早就回答了,但我编写了这个递归函数来为我在布局中找到的任何按钮设置 onClickListeners,但它可以重新调整用途:
private void recurseViews(ViewGroup v) {
View a;
boolean isgrp = false;
for(int i = 0; i < v.getChildCount(); i++) { //attach listener to all buttons
a = v.getChildAt(i);
if(a instanceof ViewGroup) setcl((ViewGroup) a);
else if(a != null) {
//do stuff with View a
}
}
return;
}
编辑:将视图转换为 ViewGroup 不会像我之前认为的那样引发异常,因此现在代码要短得多
【讨论】:
您可以使用它来获取父布局中的所有子视图,返回视图数组列表。
public List<View> getAllViews(ViewGroup layout){
List<View> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
views.add(layout.getChildAt(i));
}
return views;
}
如果你想得到一个特定的视图,你可以使用这个例子。它需要布局中的所有 TextView。
public List<TextView> getAllTextViews(ViewGroup layout){
List<TextView> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
View v =layout.getChildAt(i);
if(v instanceof TextView){
views.add((TextView)v);
}
}
return views;
}
只要您尝试获取的对象是从 View 类派生的,它就可以工作。
【讨论】: