在开发的过程中,有时候需要获取窗口的大小,在OnCreate中由于窗口还未绘制因此通过GetWidth()与GetHeight()得到的宽高都为0,那应该如何获取窗口的大小呢,上代码:
LinearLayout layout = (LinearLayout) findViewById(R.id.layout); layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){ @SuppressWarnings("deprecation") @Override public void onGlobalLayout() {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); int width = layout.getMeasuredWidth(); int height = layout.getMeasuredHeight(); }
});