Is there a way to get the row count of a GridView for Android API Level 8?
try this:
Math.ceil( (double)gridView.getCount() / (double)gridView.getNumColumns() );
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.
setHorizontalSpacing()
. If you use horizontal spacing you may need to tweak this to account for it.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);
If you take a look at the GridView page from the Android API Guide, you will see there is a method called onItemClickListener
, where one of the parameters is the position. Along with getNumColumns()
maybe you can get the number of rows.
Adding the duplicated answer here since I initially answered a duplicate question.
I added this implementation on a custom GridView subclass of mine, and it worked as expected. I checked the declared fields of the GridView class and at least on API 8 they do already have a field called mNumColumns
(which is what is returned on API 18 by getNumColumns()
). They probably haven't changed the field name to something else and then back between APIs 8 and 18, but I haven't checked.
@Override
public int getNumColumns() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return super.getNumColumns();
} else {
try {
Field numColumns = getClass().getSuperclass().getDeclaredField("mNumColumns");
numColumns.setAccessible(true);
return numColumns.getInt(this);
} catch (Exception e) {
return 1;
}
}
}
The @Override won't cause any errors since it's just a safety check annotation AFAIK.
I also don't know if there are any counter-recommendations of doing like this instead of having a separate getNumColumnsCompat()
method (as on @cottonBallPaws answer), but I found it to be pretty neat like this.