Pages

Tuesday 25 December 2012

Android - How to get Height and width of Layout??


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

5 comments :

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Replies
    1. Please explain in detail. generally this code you need to add after setcontentview in activity

      Delete
  3. Try this one

    @Override
    public void onWindowFocusChanged(boolean hasFocus)
    {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
    updateSizeInfo();
    }
    private void updateSizeInfo()
    {
    RelativeLayout rl_cards_details_card_area = (RelativeLayout) findViewById(R.id.rl_cards_details_card_area);
    w = rl_cards_details_card_area.getWidth();
    h = rl_cards_details_card_area.getHeight();
    Log.v("W-H", w+"-"+h);
    }

    ReplyDelete