我有一个 1-3 列的 GridLayout,取决于方向和屏幕大小。每个 GridLayout 项目都是带有 ImageView 和其他(带有 TextViews 等的线性布局)的垂直线性布局。图像有不同的大小。我写了一个简单的算法来裁剪图像。有时它可以正常工作(例如,当缓慢滚动时),但有时我根本看不到结果;快速滚动期间项目可能会消失。我知道 SquareImageView,但我的图像是水平的(横向),而不是方形的。我想为一行中的所有项目设置图像高度。
我的 GridView 看起来像这样:
________________ ________________
| | | |
| | | |
| ImageView | | ImageView |
| | :( |________________|
|________________| ^| LL, text, etc |
| LL, text, etc |^ |________________|
|________________|
在 setAdapter 之后:
//gvStocks is my GridView
gvStocks.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//MainHelper is an abstract class containing methods & code snippets
MainHelper.adjustImgHeights(gvStocks, firstVisibleItem, visibleItemCount);
}
});
gvStocks.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
MainHelper.adjustImgHeights(gvStocks);
if (Build.VERSION.SDK_INT >= 16)
gvStocks.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
MainHelper.adjustImgHeights:
public static void adjustImgHeights(GridView gvStocks) {
int first = gvStocks.getFirstVisiblePosition();
adjustImgHeights(gvStocks, first, gvStocks.getLastVisiblePosition() - first + 1);
}
public static void adjustImgHeights(GridView gvStocks, int firstVisibleItem, int visibleItemCount) {
int cols = gvStocks.getNumColumns();
for (int curPos = firstVisibleItem; curPos < firstVisibleItem + visibleItemCount; curPos++) {
int first = (curPos + 1) - (curPos) % cols - 1;
int minHeight = Integer.MAX_VALUE;
//get min height
for (byte b = 0; b < cols; b++) {
ViewGroup item = (ViewGroup) gvStocks.getChildAt(first + b);
if (item != null) {
ImageView iv = (ImageView) item.findViewById(R.id.ivStock);
int height = iv.getHeight();
if (height != 0) {
if (height < minHeight)
minHeight = height;
}
}
}
if (minHeight != Integer.MAX_VALUE) {
//set min height
for (byte b = 0; b < cols; b++) {
ViewGroup item = (ViewGroup) gvStocks.getChildAt(first + b);
if (item != null) {
ImageView iv = (ImageView) item.findViewById(R.id.ivStock);
iv.getLayoutParams().height = minHeight;
}
}
}
}
}
我的代码有什么问题?