Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of rows of a GridView?

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

like image 390
Hong Avatar asked Sep 01 '12 22:09

Hong


People also ask

How to get row count in Datagrid c#?

Use Property of RowCount to get the number of rows in a Data Grid View.

How do I get row count in Devexpress Gridcontrol?

To get the row number, you can use the GridView. RowCount property. To sort the grid against a column, you can use end-user capabilities (click or right-click a column header).


2 Answers

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.
like image 137
cottonBallPaws Avatar answered Oct 07 '22 14:10

cottonBallPaws


I solved the lack of getNumColumns in V8, in the case where the number of columns is specified in resource, by declaring an integer resource and using that in the GridView resource and code.

<integer name="num_grid_columns">2</integer>

<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    app:columnCount="@integer/num_grid_columns"
    app:orientation="horizontal" >

int cols = getResources().getInteger(R.integer.num_grid_columns);
like image 36
murrayr Avatar answered Oct 07 '22 12:10

murrayr