BLOKE
BLOKE

Reputation: 21

Android layoutParams getWidth() getHeight()

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' etc. Is there a way to retrieve such values too ???

Upvotes: 2

Views: 2930

Answers (1)

blessanm86
blessanm86

Reputation: 31779

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(); 

    } 
});

Upvotes: 7

Related Questions