實際開發(fā)中經(jīng)常會碰到需要獲取某個控件的寬度和高度的情況填渠,但是在實際測試中我們在Activity的啟動中期函數(shù)中廢了老大勁了钦听,我們發(fā)現(xiàn)是這樣的
OnCreate=>>>>>>>>>width==0,height==0 onStart=>>>>>>>>>width==0,height==0
onResume=>>>>>>>>>width==0,height==0
這可不就傻眼了椿争,褲子都脫了,你就給我看這個缀棍。好吧我們再嘗試一下宅此,試一試Activity的那些Hook方法內(nèi)在什么時候width與height在那個方法內(nèi)不為0,我們終于有發(fā)現(xiàn)了:
OnCreate=>>>>>>>>>width==0,height==0
onStart=>>>>>>>>>width==0,height==0
onPostCreate=>>>>>>>>>width==0,height==0
onResume=>>>>>>>>>width==0,height==0
onPostResume=>>>>>>>>>width==0,height==0
onAttachedToWindow=>>>>>>>>>width==0,height==0
onWindowFocusChanged=>>>>>>>>>width==222,height==58
是不是感覺有種千呼萬喚始出來的感覺爬范,原來在onWindowFocusChange()`方法調(diào)用的時候完成了控件的繪制父腕。有的哥們肯定要開心了,這問題就解決了坦敌,我復寫onWindowFocusChanged()方法侣诵,在這個方法內(nèi)是獲取控件的寬度和高度就可以了。當然這個方案在解決Activity內(nèi)的控件獲取高度的時候不失為一個不錯的方案狱窘,代碼量少杜顺,邏輯清晰。但是蘸炸,問題又來了躬络,雖然在 onWinodwsFocusChanged() 函數(shù)中,可以得到正確的控件尺寸搭儒。但這只在 Activity 中奏效穷当,而在 Fragment 中,該方法并不能生效淹禾。那我們又該怎么在適當?shù)臅r候獲取控件的寬度和高度呢馁菜?
下面給大家提供兩種可行的解決方案:
- 使用 ViewTreeObserver 提供的 Hook 方法。
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello_world_tv = (TextView) this.findViewById(R.id.hello_world_tv);
// 獲取View的觀察者
final ViewTreeObserver observer = hello_world_tv.getViewTreeObserver();
// 給觀察者添加布局監(jiān)聽器
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void onGlobalLayout() {
getWidthAndHeight("onGlobalLayout");
final int version = VERSION.SDK_INT;
/*
* 移除監(jiān)聽器铃岔,避免重復調(diào)用
*/
// 判斷sdk版本汪疮,removeGlobalOnLayoutListener在API 16以后不再使用
if (version >= 16) {
observer.removeOnGlobalLayoutListener(this);
} else {
observer.removeGlobalOnLayoutListener(this);
}
}
});
}
該方法在 onGlobalLayout() 方法將在控件完成繪制后調(diào)用,因而可以得到正確地結(jié)果。該方法在 Fragment 中智嚷,也可以使用卖丸。
- 使用 View 的 post() 方法
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello_world_tv = (TextView) this.findViewById(R.id.hello_world_tv);
hello_world_tv.post(new Runnable() {
@Override
public void run() {
getWidthAndHeight("post");
}
});
}
這種方法是比較簡單并可靠的做法
經(jīng)過這么一番折騰,我們可以得出android中控件的高度和寬度需要繪制完成后才能獲取到盏道。那么獲取的方法有:
1.Acyivity內(nèi)通過復寫onWinodwsFocusChanged()方法稍浆,在這個方法內(nèi)去獲取控件的相關(guān)屬性(Fragment內(nèi)不適用)
2.最優(yōu)雅的做法是調(diào)用View的post()方法
3.使用 ViewTreeObserver 注冊 OnGlobalLayoutListener