2012-04-04 36 views
3

我想盡可能動態地添加視圖到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"/> 

我的觀點在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> 

我想補充意見,佈局:

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-尺寸的視圖getheight和getwidth總是r/4406090#4406090 – 2012-04-04 07:19:13

+2

檢查此問題http://stackoverflow.com/questions/9498762/dynamically-adding-views-to-horizo​​ntal-linearlayout-goes-在屏幕外 – Nishant 2012-04-04 07:21:42

+0

「android:background =」#666「」 - 我看到你正在使用神奇數字就像我做的那樣 – 2017-02-13 16:11:43

回答

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 2012-04-04 07:31:26

+0

然後,您可以通過調用parentView.getMeasureWidth()將您的父視圖寬度放在maxWidth中。這是您的父視圖嗎? – Nishant 2012-04-04 08:40:14

+0

代碼可以幫助您嗎? – Nishant 2012-04-04 10:48:00

相關問題