Size of columns in a GridView on Android
I have in my android project a gridview which 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 gridview size to 100% of the screen and the 20% screen size for each column.
2 answers
Once you are indicating the number of columns, you can make use of android:stretchMode
to indicate that you want all columns to have the same width as a function of space:
Defines how columns should stretch to fill the available empty space, if any.
Which translated:
Defines how columns should stretch to fill any available empty space that may exist.
You need to use the constant columnWidth
that 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) .
The solution is simpler than it looks :
First: you should check if the LinearLayout
you are involving your GridView
is with android:orientation="horizontal"
, if it is not you should put.
Ps: If you are not involving it in a LinearLayout
(which would be non-standard) you should involve.
Second: you can only with a single attribute solve your problem, which would be the android:layout_weight="1"
You may ask yourself " there is but like it got 20% the size of each column if you have not set anything" - and then I answer you: putting Weight 1 it automatically distributes into 5 items per " row " or horizontally we will always have 5 columns, and if you 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: Note that I put Width 0 , because when we work with Weight, we must set the orientation size to 0, i.e. if the orientation of the LinearLayout parent was as vertical, the weight would be applied vertically, then the Height that should be 0.