[英]Programmatically Adding LinearLayouts to ScrollView
我有一个包含ScrollView (带有子LinearLayout )的xml视图。
...
<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。
问题是添加了第一行图像,但是第二行不是,因为它是在第一行附近添加(因此不在屏幕上)并且不在其下方。
如何实现我想要的输出?
将image_holder
布局中的方向设置为vertical
。 默认情况下, LinearLayout
的方向是horizontal
。 这意味着所有子视图都将添加到水平行中。 由于您的子布局使用fill_parent
作为其宽度,因此该行只能容纳一个孩子。 通过将其切换为vertical
,您的布局将添加到垂直列而不是行中。 这样可以看到更多布局。
您还应该考虑改用GridLayout
。 正是出于这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.