2012-04-04 56 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