2012-04-04 6 views
3

가능한 한 동적으로 뷰를 LinearLayout에 추가하려고합니다 (화면 너비에 따라 다름).표시하기 전에 뷰 측정 값을 계산하십시오.

LinearLayout이 화면에 표시되기 전에이 작업을 수행합니다.

내있는 LinearLayout :있는 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"/> 

내보기 :

<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> 

내가 레이아웃에 뷰를 추가

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

하지만 linearLayout.getMeasuredWidth() 및이. getWidth()는 0입니다.

내가보기에는보기 크기를 계산하기 위해 View.measure 메서드를 사용해야한다는 것을 알고 있지만 어디에서 어떻게 사용하는지 알지 못합니다. 아래

+2

가능한 속는 도움 : http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve- 가로보기 - 가로보기 - 가로보기 - 항상 - r/4406090 # 4406090 –

+2

확인이 http://stackoverflow.com/questions/9498762/dynamically-adding-views-to-horizontal-linearlayout-goes- 화면 밖에서 – Nishant

+0

"android : background ="# 666 ""- 내가하는 것처럼 마법 번호를 사용하고 있습니다. –

답변

8

편집 코드 :

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

희망이 당신의

+1

부모보기가 전체 화면 너비를 취하지 않으면? – Nik

+0

그런 다음 parentView.getMeasureWidth()를 호출하여 부모 뷰 너비를 maxWidth 내에 배치 할 수 있습니다. 여기가 부모님의 견해입니까? – Nishant

+0

코드가 도움이됩니까? – Nishant