Question

I have next view hiererchy:

     <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:gravity="center">
        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/group_bg"
            android:gravity="center_vertical" 
            android:baselineAligned="false">
            <LinearLayout
                android:id="@+id/itemplace"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="5dp"
                android:layout_weight="1" >
                <include
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/pin" />
            </LinearLayout>
            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/arrow_black"/>
        </LinearLayout>
    </LinearLayout>

I need to get itemplace width before this hierarchy will be drawing. I can not use OnLayoutChangeListener because I use API level 7.

I know that I must use measure() and layout() methods to calculate size of my views but I dont know hot it to do.

Root view in my hierarchy must fill all width of screen, so itemplace width depended of parent size, parent paddings and FrameLayout width.

What must I do to get it width?

Was it helpful?

Solution

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.

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top