原因
無(wú)法在Activity的onCreate或者onResume方法中正確的到某個(gè)View的寬/高信息辅斟,因?yàn)閂iew的measure過(guò)程和Activity的生命周期方法不是同步執(zhí)行的耘拇,因此無(wú)法保證Acitivity執(zhí)行了onCreate、onStart、onResume時(shí)某個(gè)View已經(jīng)測(cè)量好了,如果沒(méi)有測(cè)量好,那么獲得的寬/高就是0泪酱。
解決方法
1、Activity/View.onWindowFocusChanged
onWindowFocusChanged方法:View已經(jīng)初始化完畢还最,寬/高已經(jīng)準(zhǔn)備好了墓阀,這個(gè)時(shí)候獲取寬高是沒(méi)問(wèn)題的。
當(dāng)Acitivity的窗口得到焦點(diǎn)或者失去焦點(diǎn)時(shí)均會(huì)被調(diào)用一次拓轻。
public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChagned(hasFocus); if(hasFocus){ int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); } }
2斯撮、view.post(runnable)
通過(guò)post可以將一個(gè)runnable投遞到消息隊(duì)列的尾部,然后等待Looper調(diào)用此runnable的時(shí)候扶叉,View也已經(jīng)初始化好了勿锅。
protected void onStart() { super.onStart(); view.post(new Runnable() { @Override public void run() { int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); } });}
3帕膜、ViewTreeObserver
使用ViewTreeObserver的OnGlobalLayoutListener接口可以實(shí)現(xiàn)這個(gè)功能。當(dāng)View樹(shù)的狀態(tài)發(fā)生改變或者View樹(shù)內(nèi)部的View的可見(jiàn)性發(fā)生改變時(shí)溢十,onGlobalLayout方法將被調(diào)用垮刹,此時(shí)可以獲取View的寬高。
protected void onStart() { super.onStart(); ViewTreeObserver observer = view.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); } });}
手動(dòng)重寫view.measure方法獲得寬高