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);
            }
        }
        }

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

  • 相关阅读:
    ThinkPHP中PHPExcel的使用(包含日期格式)
    python学习一
    autocomplete 在火狐中文输入的问题
    NPM WARN 错误分析汇总
    react+reatrouter+redux学习笔记
    a++与++a的区别
    ES6箭头函数(Arrow Functions)
    document.referrer
    modem无法编译
    linux时钟浅析 转载
  • 原文地址:https://www.cnblogs.com/taofh/p/2267047.html
Copyright © 2011-2022 走看看