开发者

Android layoutParams getWidth() getHeight()

开发者 https://www.devze.com 2023-04-11 19:44 出处:网络
These methods return correct values when retrieved dynamically for eg. in onCreate() , but the only exception is when the dimension is specified in the xml layout file as undefined ,

These methods return correct values when retrieved dynamically for eg. in onCreate() , but the only exception is when the dimension is specified in the xml layout file as undefined , like 'wrap content' e开发者_运维知识库tc. Is there a way to retrieve such values too ???


This should return the correct width and height. onCreate is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width. Put this on the onCreate method

LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        hs.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 

    } 
});
0

精彩评论

暂无评论...
验证码 换一张
取 消