Is there a way to get the row count of a GridView for Android API Level 8?
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.