以编程方式在表格下面排列图像和按钮

时间:2014-07-16 05:17:19

标签: android layout

我正在尝试用图像和每个图像下方的搜索栏进行表格。

在我的layout.xml中:

<TableLayout
    android:id="@+id/table"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:shrinkColumns="*"
    android:stretchColumns="*" >

</TableLayout>

我是我的Main.java我循环:

// outer for loop
for (int i = 1; i <= rows; i++) {

    TableRow row = new TableRow(this);
    row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    // inner for loop
    for (int j = 1; j <= cols; j++) {

        // Picture
        ImageView image = new ImageView(this);
        image.setImageResource(R.drawable.like);                
        image.setPadding(5, 5, 5, 5);
        image.setId(1);             

        row.addView(image);

        // Seekbar
        SeekBar seekBar = new SeekBar(this);
        seekBar.setId(2);

        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        p.addRule(RelativeLayout.BELOW, image.getId());

        Log.d("BMT", Integer.toString(image.getId()));

        row.addView(seekBar, p);

    }

    table.addView(row);

}

这个结果只是带图片的桌子而没有搜索栏!我尝试了很多组合,在stackoverflow中阅读帖子,但我想我想念一些东西。请帮我理解我做错了什么。我想也许Row也应该是RelativeLayout,但它不起作用。

1 个答案:

答案 0 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

for (int i = 1; i <= rows; i++) {
    TableRow row = new TableRow(this);
    row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

     // inner for loop
     for (int j = 1; j <= cols; j++) {
         // Picture
         ImageView image = new ImageView(this);
         image.setImageResource(R.drawable.like);
         image.setPadding(5, 5, 5, 5);
         image.setId(1);

         RelativeLayout relativeLayout = new RelativeLayout(this);
         RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
         relativeLayout.setLayoutParams(p);
         relativeLayout.addView(image);

         // Seekbar
         SeekBar seekBar = new SeekBar(this);
         seekBar.setId(2);

         p.addRule(RelativeLayout.BELOW, image.getId());
         Log.d("BMT", Integer.toString(image.getId()));

         relativeLayout.addView(seekBar);
         row.addView(relativeLayout);

     }
}