Size of columns in a GridView on Android

2

I have in my android project a gridview that I define as follows:

<GridView android:id="@+id/grid1"
android:layout_width="600dp"      
android:layout_height="fill_parent"
android:padding="5dp"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:numColumns="5"
android:columnWidth="120dp"
android:gravity="center"/>

I would like to know if there is any way to set the size of the gridview to 100% of the screen and the size of 20% of the screen for each column.

    
asked by anonymous 21.02.2014 / 21:14

2 answers

1

Since you're reporting the number of columns, you can use android:stretchMode to indicate that you want all columns to have the same width as space:

  

Define how columns should stretch to fill the available empty space, if any.

What translated:

  

Defines how columns should be stretched to fill the available empty space that may exist.

You need to use the constant columnWidth which indicates that each column is stretched equally:

android:stretchMode="columnWidth"

In your code:

<GridView android:id="@+id/grid1"
android:layout_width="600dp"      
android:layout_height="fill_parent"
android:padding="5dp"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:numColumns="5"
android:columnWidth="120dp"
android:stretchMode="columnWidth"
android:gravity="center"/>

For non-XML version, see gridView.setStretchMode (GridView.STRETCH_COLUMN_WIDTH) (English) .

    
21.02.2014 / 21:59
0

solution is simpler than it looks :

First: You should check if the LinearLayout you are involving your GridView is with android:orientation="horizontal" , if not you should put it. Ps: If you're not wrapping it in a LinearLayout (which would be out of the standard) you should wrap.

Second: You can only with a single attribute solve your problem, which would be android:layout_weight="1"

You may ask yourself, "But what about 20% the size of each column if you did not even set anything?" - and then I answer: Putting Weight 1 it automatically distributes itself in 5 items by "line" or horizontally we will always have 5 columns, and if you will see:

(10/5itens) = 2 ----> 2 = 20% ----> 10 = 100%

Getting this way:

<GridView android:id="@+id/grid1"
android:layout_width="0dp"
android:layout_weight="1"      
android:layout_height="fill_parent"
android:padding="5dp"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:numColumns="5"
android:columnWidth="120dp"
android:gravity="center"/>

Result:

Note:NotethatIputWidth0,becausewhenworkingwithWeight,weshouldsettheorientationsizeto0,thatis,iftheorientationoftheparentLinearLayoutwasasvertical,theweightwouldbeappliedvertically,thentheHeightthatshouldbe0.

Foryourbetterunderstanding,Irecommendreading my answer to another question

    
22.02.2014 / 00:28