Activity 中擷取所有控制項 並設定自訂字型

來源:互聯網
上載者:User
最近我在面試Android工程師的時候出過一個題目:怎麼擷取當前Activity中的所有控制項,基本大多數人茫然了,不知道怎麼去做。可能是我出的題目有些操蛋吧。我把My Code貼出來,大家打擊批評吧。

 

.....

 

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

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

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.