Search code examples
androidgridviewcenterchildren

center gridview columns in row


I have a gridview, with a set number of columns (let's say, 5). However, if I have 6 images set in my image adapter, the 6th one automatically goes to a new row, and is assigned the first column. The behavior I am looking for would be to automatically (or programmatically, somehow) center that extra child element in the new row... like this for example:

A B C D E
    F

Here is the XML that I have for the gridview:

<GridView android:id="@+id/gridview" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:columnWidth="10dip"
android:numColumns="10" android:horizontalSpacing="10dip"
android:stretchMode="columnWidth"
xmlns:android="http://schemas.android.com/apk/res/android"
android:verticalSpacing="3dp"
android:layout_below="@+id/TopLayout"
android:layout_gravity="center"></GridView>

Solution

  • You can't change the number of cols for a given row. The only trick I can think of is to use an odd number of columns and insert void entries in the list your adapter is based on. E.g. if you have 5 cols and 6 images, insert 2 void entries at positions 5 and 6 so your last image will be centered.