如何使用两列ScrollView?

时间:2012-06-16 13:24:04

标签: android android-layout android-scrollview

我想要一个2列ScrollView。在每列中,应该有一个ImageButton

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_height="800dp"
android:background="#FFF"
android:layout_width="600dp" >

<LinearLayout
    android:id="@+id/categoryLinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</LinearLayout>

</ScrollView>

代码:

        LinearLayout sv = (LinearLayout) findViewById(R.id.categoryLinearLayout1);

    for (int i = 0; i < 10; i++) {
        ImageButton ib = new ImageButton(this);
        // ib.setImageDrawable(getResources().getDrawable(R.drawable.cat1));

        Bitmap bmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.cat1);
        int width = 300;
        int height = 300;
        Bitmap resizedbitmap = Bitmap.createScaledBitmap(bmp, width,
                height, true);
        ib.setImageBitmap(resizedbitmap);
        sv.addView(ib);
    }

但是这样,所有10 ImageButtons水平。我需要的是,将2 ImageButton连续放入(它生成600px)并向下放置,放置更多2 ImageButtons等等。因此,10 ImageButtons将有5行。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用TableLayout

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView1"
android:layout_height="800dp"
android:background="#FFF"
android:layout_width="600dp" >

<TableLayout
    android:id="@+id/categoryLinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</TableLayout>

</ScrollView>

然后在你的代码中:

TableLayout sv = (TableLayout) findViewById(R.id.categoryLinearLayout1);

for (int i = 0; i < 5; i++) {
    TableRow tr = new TableRow(this);
    tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
    for (int j = 0; j < 2; j++) {
         ImageButton ib = new ImageButton(this);
         // ib.setImageDrawable(getResources().getDrawable(R.drawable.cat1));
         Bitmap bmp = BitmapFactory.decodeResource(getResources(),
              R.drawable.cat1);
         int width = 300;
         int height = 300;
         Bitmap resizedbitmap = Bitmap.createScaledBitmap(bmp, width,
            height, true);
         ib.setImageBitmap(resizedbitmap);
         ib.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
         tr.addView(ib);
     }
     sv.add(tr); 
}