public class MyActivity extends Activity {
......
//获取当前Activity里所有控件
public List<View> getAllChildViews() {
View view = this.getWindow().getDecorView();
return getAllChildViews(view);
}
//获取指定View里所有控件
public List<View> getAllChildViews(View view) {
List<View> allchildren = new ArrayList<View>();
if (view instanceof ViewGroup) {
ViewGroup vp = (ViewGroup) view;
for (int i = 0; i < vp.getChildCount(); i++) {
View viewchild = vp.getChildAt(i);
allchildren.add(viewchild);
allchildren.addAll(getAllChildViews(viewchild));
}
}
return allchildren;
}
}
View view = this.getWindow().getDecorView();
return getAllChildViews(view);
}
//获取指定View里所有控件
public List<View> getAllChildViews(View view) {
List<View> allchildren = new ArrayList<View>();
if (view instanceof ViewGroup) {
ViewGroup vp = (ViewGroup) view;
for (int i = 0; i < vp.getChildCount(); i++) {
View viewchild = vp.getChildAt(i);
allchildren.add(viewchild);
allchildren.addAll(getAllChildViews(viewchild));
}
}
return allchildren;
}
当然,这代码也是有问题的,就是无法得到ListView这类控件的所有Item,应为ListView不是继承ViewGroup ,这是个鸡肋方法,很少用,如果大家有兴趣的话,可以帮忙改进写。
得到当前Activity里的所有控件,有什么用呢,我主要是为了给当前Activity设置自定义字体。
private void setTypeface(Typeface typeface) {
List<View> children = getAllChildViews();
for (View child : children) {
if (child instanceof TextView) {
TextView tv = (TextView) child;
tv.setTypeface(typeface);
}
}
}
List<View> children = getAllChildViews();
for (View child : children) {
if (child instanceof TextView) {
TextView tv = (TextView) child;
tv.setTypeface(typeface);
}
}
}