Skip to content Skip to sidebar Skip to footer

Getnumcolumns() For Api 8

getNumColumns() for GridView is available since API 11, is there any way to get this method in API 8?

Solution 1:

in this duplicated post, someone came with an answer which works for API 8 :

privateintgetNumColumnsCompat() {
    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)
privateintgetNumColumnsCompat11() {
    return getNumColumns();
}

Solution 2:

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.

@Overridepublic int getNumColumns() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        returnsuper.getNumColumns();
    } else {
        try {
            Field numColumns = getClass().getSuperclass().getDeclaredField("mNumColumns");
            numColumns.setAccessible(true);
            return numColumns.getInt(this);
        } catch (Exception e) {
            return1;
        }
    }
}

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 @elgui answer), but I found it to be pretty neat like this.

Solution 3:

This probably isn't an answer you want to hear but you'll have to create a custom GridView' with it's API 11 functionality that fits with what's available in API 8.

Solution 4:

Joining best answers, and boiling up:

@SuppressLint("NewApi")@OverridepublicintgetNumColumns() {
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) 
      returnsuper.getNumColumns();

   try {
      FieldnumColumns= getClass().getSuperclass().getDeclaredField("mNumColumns");
      numColumns.setAccessible(true);
      return numColumns.getInt(this);
   }
   catch (Exception e) {}

   intcolumns= AUTO_FIT;
   if (getChildCount() > 0) {
      intwidth= getChildAt(0).getMeasuredWidth();
      if (width > 0) columns = getWidth() / width;
   }
   return columns;
}

:D

Post a Comment for "Getnumcolumns() For Api 8"