簡體   English   中英

以編程方式將LinearLayouts添加到ScrollView

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM