Calculate measure before displaying

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

I do this before the LinearLayout appears on the 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 have to use the View.measure method to calculate the size of the view before it becomes visible, but I don't know where or how it is used.

+3


source to share


1 answer


Modify your code as shown 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

+8


source







All Articles