2013-03-20 157 views
0

我有一个xml视图,其中包含一个ScrollView(带子LinearLayout)。将LinearLayouts添加到滚动视图

... 
    <ScrollView 
     android:id="@+id/scrollView_container" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_alignParentLeft="true" 
     android:layout_marginTop="33dp" > 

     <LinearLayout 
      android:id="@+id/image_holder" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" > 
     </LinearLayout> 
    </ScrollView> 
... 

我试图动态地添加一些图片,我想3每行。

private void createDice(LinearLayout ll, Integer required) { 
    ArrayList<Integer> images = new ArrayList<Integer>(); 
    images.add(R.drawable.one); 
    images.add(R.drawable.two); 
    images.add(R.drawable.three); 
    images.add(R.drawable.four); 
    images.add(R.drawable.five); 
    images.add(R.drawable.six); 

    ScreenHelper screen = new ScreenHelper(MainActivity.this); 
    Map<String, Float> s = screen.getScreenSize(); 
    Integer maxPerRow = (int) (s.get("width")/90); // images are 89px wide 
    Log.d(TAG, "max across::"+maxPerRow); 

    Integer rows = (required/maxPerRow); 
    Log.d(TAG, "rows::"+rows); 
    for (int i=0; i < rows; i++) { 
     Log.d(TAG, "i::"+i); 
     // create linear layout for row 
     LinearLayout llAlso = new LinearLayout(this); 
     llAlso.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
     //llAlso.setOrientation(LinearLayout.HORIZONTAL); 

     for (int j=0; j < 3; j++) { 
      Log.d(TAG, "j::"+j); 
      // create/add image for the row 
      ImageView iv = new ImageView(this); 
      iv.setImageResource(images.get(i)); 
      llAlso.addView(iv); 
     } 
     // add to main layout 
     ll.addView(llAlso, i); 
     Log.d(TAG, "adding to main view"); 
    } 
} 

我正在与6.
问题所需参数值测试的是,图像的第一行被添加,但是因为它是获取添加邻近任一第二不第一行(因此不在屏幕上)而不在其下面。

关于如何实现我想要的输出的任何想法?

+0

这听起来像你正在努力完成的非常适合'GridView',以及为什么你反对使用它? – 2013-03-20 16:56:29

+0

@BrentHronik我不反对使用GridView(现在我知道),但即使不是最好的方法,我仍然愿意完成我开始的任务。 – Rooneyl 2013-03-20 17:05:46

回答

4

image_holder布局中的方向设置为vertical。默认情况下,LinearLayout的方向为horizontal。这意味着所有的子视图都将被添加到水平行中。由于您的孩子布局使用宽度为fill_parent,所以只有一个孩子可以放入该行。通过将其切换为vertical,您的布局将添加到垂直列中而不是连续添加。这可以让更多布局可见。

此外,你应该考虑使用GridLayout来代替。这是针对这种情况。

+0

谢谢,这是有效的。你能解释一下为什么这么做吗? – Rooneyl 2013-03-20 16:56:35

+1

@Rooneyl默认情况下,“LinearLayout”的方向为“水平”。这意味着所有的子视图都将被添加到水平行中。由于您的子布局在其宽度上使用'fill_parent',因此只有一个孩子可以放入该行。通过将其切换到“垂直”,您的布局将添加到垂直列中,而不是连续添加。这可以让更多布局可见。 – MCeley 2013-03-20 17:05:06

+0

@MCeley感谢您的解释 – Rooneyl 2013-03-20 17:06:23

相关问题