Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center elements in GridView

I have GridView with 6 images in 2 columns. I want to display this 6 images in the middle of the screen. I set gravity properties to center but this center elements only horizontally. GridView takes whole screen.

<GridView     android:id="@+id/gridview"     android:layout_above="@id/ad" android:layout_alignParentTop="true"     android:layout_width="fill_parent"      android:layout_height="fill_parent"      android:numColumns="2"         android:verticalSpacing="10dp"     android:horizontalSpacing="10dp"     android:stretchMode="columnWidth"            android:background="#ffffff"     android:gravity="center" /> 
like image 856
bimbol Avatar asked Jan 27 '11 11:01

bimbol


People also ask

How do I center something in GridView?

Answers. . Click on the gridView->properties->RowStyle:horizontal-align:Center // what ever you want.

How do you center grid view in flutter?

There is a very simple way. Just set shrinkWrap: true which makes the GridView to take minimum space and wrap the GridView with Center widget.


2 Answers

Here is what I did to get the items in the gridview to center (notice the stretchmode, columnwidth, gravity and horizontal and vertical spacing):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="horizontal"     android:padding="5dp" >     <GridView         android:id="@+id/gridview"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:columnWidth="100dp"         android:gravity="center"         android:horizontalSpacing="10dp"         android:numColumns="3"         android:stretchMode="spacingWidthUniform"         android:verticalSpacing="10dp" /> </LinearLayout> 

It took me a while to figure it out, but messing with those different values I was able to get them to center.

like image 151
Ray Hunter Avatar answered Nov 08 '22 12:11

Ray Hunter


Try wrapping your GridView in a LinearLayout that has it's child elements centered and change your gridview's layout_height to "wrap_content". ex:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:layout_height="fill_parent"   android:layout_width="fill_parent"   android:gravity="center"   android:layout_gravity="center">     <GridView        android:id="@+id/homeGridView"       android:layout_width="fill_parent"       android:layout_height="wrap_content"       android:numColumns="3"       android:verticalSpacing="10dp"       android:horizontalSpacing="10dp"       android:stretchMode="columnWidth"       android:gravity="center" /> </LinearLayout> 
like image 24
Nelson Monterroso Avatar answered Nov 08 '22 12:11

Nelson Monterroso