Skip to content Skip to sidebar Skip to footer

Measure All View Hierarchy Before Drawing In Android

I have next view hiererchy:

Solution 1:

I have find out way to get view width. I can get it after android measuret it but before drawing using OnPreDrawListener in ViewTreeObserver:

    view.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener()
    {
        @Override
        public boolean onPreDraw()
        {
            int avaliableWidth = view.getWidth() - view.getPaddingLeft() - view.getPaddingRight();

            Log.d("width", String.valueOf(avaliableWidth));

            return true;
        }
    });

From Android documentation:

Callback method to be invoked when the view tree is about to be drawn. At this point, all views in the tree have been measured and given a frame. Clients can use this to adjust their scroll bounds or even to request a new layout before drawing occurs.


Solution 2:

This is available since API 1:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
}

Post a Comment for "Measure All View Hierarchy Before Drawing In Android"