Calculate view measure before display it

Nik picture Nik · Apr 4, 2012 · Viewed 16.4k times · Source

I am trying to add views to LinearLayout dynamically as much as it possible (depending on screen width).

I do this before the LinearLayout displays on screen.

My LinearLayout:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center" 
    android:background="#666"/>

My view to display in LinearLayout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp"
    android:background="#999">
    <ImageView
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:src="@drawable/no_photo"/>
</FrameLayout>

I add views to layout:

int allItems = 50;
int currentItem = 0;
while(currentItem < allItems)
{
    FrameLayout view = (FrameLayout) inflater.inflate(R.layout.fl, null);

    linearLayout.addView(view);

    if (linearLayout.getMeasuredWidth() >= this.getWidth())
    {
        linearLayout.removeView(view);
        break;
    }
}

but linearLayout.getMeasuredWidth() and this.getWidth() is 0;

I know, that i must use View.measure method to calculate view size before it became visible, but i don't know where and how it use.

Answer

Nishant picture Nishant · Apr 4, 2012

Edit your code as below :

Display display = getWindowManager().getDefaultDisplay();
int maxWidth = display.getWidth();
int widthSoFar=0;

int allItems = 50;
int currentItem = 0;

while(currentItem < allItems) {
  FrameLayout view = (FrameLayout) inflater.inflate(R.layout.fl, null);

  linearLayout.addView(view);

  view .measure(0, 0);
  widthSoFar = widthSoFar + view.getMeasuredWidth();


  if (widthSoFar >= maxWidth) {
    linearLayout.removeView(view);
    break;
  }
}

Hope this helps you