有時候須要在onCreate方法中知道某個View組件的寬度和高度等信息,而直接調用View組件的getWidth()、getHeight()、getMeasuredWidth()、getMeasuredHeight()、getTop()、getLeft()等方法是沒法獲取到真實值的,只會獲得0。這是由於View組件佈局要在onResume回調後完成。下面提供實現方法,onGlobalLayout回調會在佈局完成時自動調用 ide
final LinearLayout imageViewContainer = (LinearLayout)findViewById(R.id.crop_photo_image_view_container);
imageViewContainer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
boolean isFirst = true;//默認調用兩次,這裏只讓它執行一次回調
@Override
public void onGlobalLayout() {
if (isFirst) {
isFirst = false;
//如今佈局所有完成,能夠獲取到任何View組件的寬度、高度、左邊、右邊等信息
Log.i("CDH", "Global W:"+imageViewContainer.getMeasuredWidth()+" H:"+imageViewContainer.getMeasuredHeight());
}
}
}); 佈局