我正在尝试显示图像网格(我知道在执行时会有多少图像)。我的问题是这个网格必须在一个垂直的ScrollView里面和ViewPager里面,所以不鼓励将两个可滚动的视图放在另一个里面,我不能使用水平的GridLayout因为我在ViewPager中所以水平滚动已经很好了。
所以我试图使用TableLayout实现这一点,并使用一些数学手动设置所有填充/边距/尺寸。我得到的是这个:
我能做些什么来实现这些结果吗?
可能使用固定高度和宽度的GridLayout ..
到目前为止我编写的用于填充TableLayout的代码报告如下。它在片段中,“act”是对活动的引用,table_view是我的TableLayout,objectids是一个包含要使用的图像的ID的LinkedList。
private void calculateGrid() {
table_view.removeAllViews();
table_view.setVisibility(View.VISIBLE);
int minLato = Math.min(act.metrics.widthPixels, act.metrics.heightPixels);
float density = act.metrics.density;
int screenX = (int) (minLato / act.metrics.density);
float factor = 4f;
int imageXpx = (int) (minLato / factor);
int imageX = (int) (imageXpx / act.metrics.density);
int margins;
int numImage = objectids == null ? 0 : objectids.size();
int numRow;
int numCol;
int gridY; // = ?
int countImg = 1;
if (screenX % imageX == 0) { // TODO poi sarà un po piu di 0 per non avere margini minuscoli
numCol = screenX / imageX - 1;
margins = imageX / (screenX / imageX);
} else {
numCol = screenX / imageX;
margins = (screenX % imageX) / (screenX / imageX + 1);
}
margins = Math.min(10, margins);
int dpMargins = (int) (margins * density);
numRow = (int) Math.ceil(numImage / (double) numCol);
gridY = numRow * (margins * 2 + imageX);
Log.e(TAG, "dens: " + density + " screen: " + screenX + " img: " + imageX + " margins: " + margins + " numImg: " + numImage + " numRow: " + numRow
+ " numCol" + numCol + " gridY: " + gridY);
List<TableRow> rows = new LinkedList<TableRow>();
int ID = 1000;
TableRow oneRow;
TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
tableParams.gravity = Gravity.CENTER;
for (int i = 1; i <= numRow; i++) {
Log.d(TAG, "row " + i);
oneRow = new TableRow(ctx);
oneRow.setLayoutParams(tableParams);
for (int k = 1; k <= numCol; k++) {
Log.d(TAG, "col " + k);
if (countImg <= numImage) {
Log.i(TAG, "img " + countImg);
ImageView img = new ImageView(ctx);
TableRow.LayoutParams rp = new TableRow.LayoutParams(imageXpx, imageXpx);
rp.bottomMargin = dpMargins;
rp.topMargin = dpMargins;
rp.leftMargin = dpMargins;
rp.rightMargin = dpMargins;
img.setLayoutParams(rp);
img.setId(ID + countImg);
img.setScaleType(ImageView.ScaleType.CENTER_CROP);
loadBitmaps(ctx, app.getDatabase(), img, objectids.get(countImg - 1), "image", target_graphid, ticket);
img.setImageResource(R.drawable.capiicona);
oneRow.addView(img);
countImg++;
}
}
rows.add(oneRow);
}
for (TableRow tr : rows)
table_view.addView(tr);
table_view.setGravity(Gravity.CENTER_HORIZONTAL)
}
感谢您的宝贵帮助。