Pages

Tuesday, October 14, 2014

ViewTreeObserver - How to get layout width and height run time in android?

Example code for how to use ViewTreeObserver to get run time get layout height and width in Androd.

You can add a tree observer to the layout. 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() { 
        this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight();
  //TODO: code
  System.out.println("Layout Height : "+height+ "and Layuot Width : "+width);
    } 
});


Thank you :)

No comments:

Post a Comment