Activity 中获取所有控件 并设置自定义字体
最近我在面试Android工程师的时候出过一个题目:怎么获取当前Activity中的所有控件,基本大多数人茫然了,不知道怎么去做。可能是我出的题目有些操蛋吧。我把我的代码贴出来,大家打击批评吧。
.....
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);
}
}
}
如果有人有更好的解决方案,不妨分享写。