我正在尝试在运行时将另一个RelativeLayout
下的一系列图像添加到当前TextView
。到目前为止,我得到它显示部分正确,但不完全正确。我不能让他们搬到另一排。我希望有人可以帮我一把,告诉我正确的方法。系列图片将显示在此TextView
(R.id.date
):
TextView date = (TextView) findViewById(R.id.date);
//// image view start //////
int photos = Integer.parseInt(total_photo);
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relative_layout_b);
for (int i = 0; i < limit; i++){
final ImageView imageView = new ImageView (this);
imageView.setId(i);
imageView.setImageResource(R.drawable.photo_frame);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
imageView.setPadding(10, 10, 0, 0);
imageView.setAdjustViewBounds(true);
imageView.setMaxHeight(80);
imageView.setMaxWidth(80);
lp.addRule(RelativeLayout.BELOW, R.id.date);
lp.addRule(RelativeLayout.RIGHT_OF, imageView.getId() - 1);
imageView.setLayoutParams(lp);
mainLayout.addView(imageView);
}
现在,它只显示总照片数量 - 1(即:当有5时,它只显示4);并且我想让每一行显示5并且如果它达到6,11,16等等将立即移动到下一行。此布局嵌套在ScrollView
和RelativeLayout
中,因为我有很多视图。所以,我必须坚持使用RelativeLayout
。
答案 0 :(得分:1)
如果我理解了您要做的事情,请查看下面的代码是否符合您想要的ImageViews
(我不知道它的效率如何):
private static final int ROW_ITEMS = 5; // 5 ImageViews per row
// ...
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relative_layout_b);
int limit = 13; // I assume that limit is the number of ImageView that you'll put in the layout
int rows = limit / ROW_ITEMS; // the number of rows that results from limit
int leftOver = limit % ROW_ITEMS; // see if we have incomplete rows
if (leftOver != 0) {
rows += 1;
}
int id = 1000; // the ids of the ImageViews 1000, 1001, 1002 etc
int belowId = R.id.date; // this id will be used to position the ImageView on another row
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++) {
final ImageView imageView = new ImageView(this);
imageView.setId(id);
imageView.setImageResource(R.drawable.ic_launcher);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
imageView.setPadding(10, 10, 0, 0);
imageView.setAdjustViewBounds(true);
imageView.setMaxHeight(80);
imageView.setMaxWidth(80);
if (i == 0) {
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
} else {
lp.addRule(RelativeLayout.RIGHT_OF, imageView.getId() - 1);
}
lp.addRule(RelativeLayout.BELOW, belowId);
imageView.setLayoutParams(lp);
mainLayout.addView(imageView);
id++;
}
belowId = id - 1;
rows--;
}
另外,正如kcoppock在评论中已经说过的那样,为了提高效率可能值得GridView
。