我需要类似于网格布局的东西,但是要具有元素定位的自己的逻辑。我扩展了Frame Layout,并编写了以下逻辑:
单元格应该是正方形,布局只能在宽度上增长并存储在HorizontalScrollView中。问题在于函数
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
int childCount = getChildCount();
if (childCount==0) return;
int cellSize= 0;
for (int i=0;i<getChildCount();i++) {
cellSize = Math.max(cellSize, getChildAt(i).getMeasuredHeight());
}
cellSize= Math.min(getMeasuredHeight()/rowCount,cellSize);
if (autoColumnCount&&cellSize>0) {
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int screenWidth = displaySize.x;
columnCount = Math.max(screenWidth/cellSize - autoColumnOffset,1);
}
cellSize = cellSize - cellPadding*2;
ArrayList<ArrayList<Integer>> sortedIndexes = new ArrayList<>();
int currentIndex=0;
while (true) {
if (currentIndex>=childCount) break;
ArrayList<Integer> indexes = new ArrayList<>();
indexes.add(currentIndex);
for (int y=1;y<rowCount;y++) {
int index = currentIndex + (y*columnCount);
if (index<childCount)
indexes.add(index);
else
break;
}
sortedIndexes.add(indexes);
currentIndex++;
if (currentIndex%columnCount==0) {
currentIndex = (currentIndex-columnCount)+(rowCount*columnCount);
}
}
int maxRows = 1;
for (int i=0;i<rowCount;i++) {
for (int y=0;y<sortedIndexes.size();y++) {
ArrayList<Integer> indexes = sortedIndexes.get(y);
if (i<indexes.size()) {
maxRows = Math.max(maxRows,i+1);
View v = getChildAt(indexes.get(i));
int newX = y*cellSize+(y+1)*cellPadding+y*cellPadding;
int newY = i*cellSize+(i+1)*cellPadding+i*cellPadding;
int measureSpecWidth = MeasureSpec.makeMeasureSpec(Math.min(cellSize,v.getMeasuredWidth()), MeasureSpec.AT_MOST);
int measureSpecHeight = MeasureSpec.makeMeasureSpec(Math.min(cellSize,v.getMeasuredHeight()), MeasureSpec.AT_MOST);
v.measure(measureSpecWidth, measureSpecHeight);
centerViewInBounds(v, newX, newY, newX + cellSize, newY + cellSize);
}
}
}
final int neededHeight = maxRows*cellSize+maxRows*cellPadding*2;
final int neededWidth = sortedIndexes.size()*cellSize+sortedIndexes.size()*cellPadding*2;
MyLog.print("asd", "Column count: " + sortedIndexes.size() + "\nCell size (with padding): " + (cellSize + cellPadding * 2) + "\nWidth: " + neededWidth);
setMeasuredDimension(neededWidth, neededHeight);
单元格应该是正方形,布局只能在宽度上增长并存储在HorizontalScrollView中。问题在于函数
setMeasuredDimension
的工作不正确或我收到的大小是错误的(尽管我认为一切都应该正常工作):按照这种逻辑,我得到了下面的结果:
问题出在哪里?提前感谢您的帮助。