Android:使站在GridView的一行中的ImageViews具有相同的高度

时间:2015-08-12 15:33:39

标签: java android gridview adaptive-design adaptive-layout

我有一个包含1-3列的GridLayout,取决于方向和&屏幕尺寸。每个GridLayout项都是一个带ImageView的垂直LinearLayout和其他(带有TextViews的LinearLayout等)。图像有不同的大小。我写了一个简单的算法来裁剪图像。有时它工作正常(例如,当慢慢滚动时),但有时我根本看不到结果;在快速滚动期间,项目可能会消失。 我知道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;
                }
            }
        }
    }
}

我的代码出了什么问题?

0 个答案:

没有答案