34

im trying to get images displayed in a GridView and get the columns automatically set, so far I've had to manually set the number of columns which is not what i want to do as this will affect how big the images are on different sized screens. I ahve tried setting it to auto_fit but it only displays 2 columns in the middle of the screen. This is what im trying to achieve: (Each red square represents an image)

enter image description here

then when turned to landscape mode i want the columns to auto fit so that its all even. Any help would be much appreciated, thank you :)

Tom O
  • 1,780
  • 2
  • 20
  • 43

3 Answers3

76

Experiment with the GridView attributes, specifically android:numColumns="auto_fit" and android:stretchMode. The following works for me:

<GridView 
    android:id="@+id/myGrid"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:numColumns="auto_fit"
    android:columnWidth="60dp"
    android:stretchMode="columnWidth"    
    android:gravity="center"
/>
Jeff Gilfelt
  • 26,131
  • 7
  • 48
  • 47
  • 5
    Brilliant. I had auto_fit, but was missing columnWidth. After I added that, things started working beautifully. – Artem Russakovskii Sep 14 '11 at 02:22
  • I had everything except the columnWidth param, which is mandatory to have anything out of 2 columns – njzk2 Nov 07 '11 at 15:24
  • 2
    I have the same exact XML but still the GridView shows only 2 columns! – Ε Г И І И О Jun 13 '13 at 18:57
  • @ΕГИІИО If you don't specify columnWidth you will get 2 columns by default, as looking at GridView's source code would tell you. You can use my solution (specified here) for those cases. – Vaiden Nov 11 '13 at 12:55
13

I'm not sure why someone voted down the answer above me (so I voted it up again): I had to solve a similar problem programatically (with a GridView of ImageView children). Some code removed for clarity:

    int iDisplayWidth = getResources().getDisplayMetrics().widthPixels ;

    iImageWidth = iDisplayWidth
        / iNumberOfColumns ; 
    gridview.setColumnWidth( iImageWidth );
    gridview.setStretchMode( GridView.NO_STRETCH ) ;    
    /* wrap_content in the xml file is supposed to do this, but it didn't seem to work */

Best regards,

Piesia

Piesia
  • 185
  • 3
  • 8
5

A better solution is to measure the width programmatically, so you won't end up with a hard-coded column width:

Android: How does GridView auto_fit find the number of columns?

Community
  • 1
  • 1
Vaiden
  • 15,728
  • 7
  • 61
  • 91