程序化ImageView android重复行

时间:2012-09-12 20:41:25

标签: android layout imageview

所以我有一个Android应用程序的功能,应该采取任意数量的图片,并显示每行5个图片,由于某种原因,当它进入第二行,它只是重复第一行的图片例如,如果我有7张图片编号为1-7,他们将显示: 12345 12 这是我的功能,感谢任何建议。

public void generateImageView(int number, String path){
        //ImageView[] imageViewArray = new ImageView[number];
        int ROW_ITEMS = 5; // 5 images per row
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.RelativeLayout1);
        int limit = number;//limits the number of created imageViews to number
        int rows = limit / ROW_ITEMS;//number of rows
        int leftOver = limit % ROW_ITEMS; //see if we have incomplete rows
        if (leftOver != 0){
            rows += 1;
        }
        int id = 1000;
        int belowId = R.id.send;
        while (rows > 0){
            int realItemsPerRow = ROW_ITEMS;
            if (leftOver != 0 & rows == 1){
                realItemsPerRow = Math.min(ROW_ITEMS,  leftOver);
            }

        for (int i = 0; i < realItemsPerRow; i++){

            Bitmap myBitmap = BitmapFactory.decodeFile(path + i + ".png");
            ImageView imageViewArray = new ImageView(MainActivity.this);
            imageViewArray.setId(id);
            imageViewArray.setImageBitmap(myBitmap);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            imageViewArray.setPadding(10,10,0,0);
            imageViewArray.setAdjustViewBounds(true);
            imageViewArray.setMaxHeight(80);
            imageViewArray.setMaxWidth(80);
            if (i==0) {
                lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
            } else {
                lp.addRule(RelativeLayout.RIGHT_OF, imageViewArray.getId() -1);
            }
            lp.addRule(RelativeLayout.BELOW, belowId);

            imageViewArray.setLayoutParams(lp);

            rl.addView(imageViewArray);
            id++;
        }
        belowId = id - 1;
        rows--;

1 个答案:

答案 0 :(得分:1)

这是因为你只是为行中的每个位置拉相同的图像:

Bitmap myBitmap = BitmapFactory.decodeFile(path + i + ".png");

while( rows > 0 )之前添加:

int j = 0;

然后将上述内容更改为:

Bitmap myBitmap = BitmapFactory.decodeFile(path + ( j * ROW_ITEMS + i ) + ".png");

并在rows--;下添加:

j++;