zoukankan      html  css  js  c++  java
  • 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;
        }
     }

    当然,这代码也是有问题的,就是无法得到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);
            }
        }
        }

    如果有人有更好的解决方案,不妨分享写。

  • 相关阅读:
    2 安装部署flume
    1 flume快速入门——十分钟学会flume
    3、剑指offer-数组——数组中重复的数字
    3.kafka安装配置
    2、剑指offer-字符串——替换空格
    1、剑指offer-数组——二维数组中的查找
    JVM虚拟机垃圾回收(GC)算法及优缺点
    Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/collect/ImmutableMap
    LeetCode 617. 合并二叉树 Java
    Linux命令大全
  • 原文地址:https://www.cnblogs.com/taofh/p/2267047.html
Copyright © 2011-2022 走看看