How to get the number of rows of a GridView?

前端 未结 5 874
梦如初夏
梦如初夏 2021-02-07 20:53

Is there a way to get the row count of a GridView for Android API Level 8?

5条回答
  •  死守一世寂寞
    2021-02-07 21:20

    I had to solve this last night and it worked for me. It looks up a child's width and assuming all cells have the same width, divides the GridView's width by the child's width. (getColumnWidth() is also unavailable in earlier APIs, so hence the workaround).

    private int getNumColumnsCompat() {
        if (Build.VERSION.SDK_INT >= 11) {
            return getNumColumnsCompat11();
    
        } else {
            int columns = 0;
            int children = getChildCount();
            if (children > 0) {
                int width = getChildAt(0).getMeasuredWidth();
                if (width > 0) {
                    columns = getWidth() / width;
                }
            }
            return columns > 0 ? columns : AUTO_FIT;
        }
    }
    
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private int getNumColumnsCompat11() {
        return getNumColumns();
    }
    

    However there are some important restrictions to note with this.

    • It will only work after the GridView is laid out and only when it actually has some views added to it.
    • This doesn't take into account any cell spacing added with setHorizontalSpacing(). If you use horizontal spacing you may need to tweak this to account for it.
    • In my case I didn't have any paddings or additional width to account for. If you do, you will need to tweak this to ensure the division ends up with the right answer.

提交回复
热议问题