Android: center gridview horizontally

17,731

Solution 1

I centered my grid view manually, by calculating and setting its padding. Here's what my onCreate does:

  • find out width of the screen and screen density
  • convert constant values for item width and spacing from DIP to pixels
  • calculate number of columns I can fit.

Equation looks like this, numColumns is the only unknown:

numColumns * itemWidth + (numColumns - 1) * spacingBetweenItems + selectorPadding <= sreenWidth

  • having numColumns, calculate how much horizontal space my grid view will actually need
  • having actual width of grid view, set padding so that it ends up in the center of screen

OK, and here's some code:

// Convert DIPs to pixels
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mSizePx = (int) Math.floor(SIZE_DIP * metrics.scaledDensity);
mSpacingPx = (int) Math.floor(SPACING_DIP * metrics.scaledDensity);

GridView gridview = (GridView) findViewById(R.id.gridview);
// Find out the extra space gridview uses for selector on its sides.
Rect p = new Rect();
gridview.getSelector().getPadding(p);
int selectorPadding = p.left + p.right;

// Determine the number of columns we can fit, given screen width,
// thumbnail width, and spacing between thumbnails.
int numColumns = (int) Math.floor(1f * (metrics.widthPixels - selectorPadding + mSpacingPx)
        / (mSizePx + mSpacingPx));

int contentWidth = numColumns * mSizePx; // Width of items
contentWidth += (numColumns - 1) * mSpacingPx; // Plus spaces between items
contentWidth += selectorPadding; // Plus extra space for selector on sides

// Now calculate amount of left and right margin so the grid gets
// centered. This is what we
// unfortunately cannot do with layout_width="wrap_content"
// and layout_gravity="center_horizontal"
int slack = metrics.widthPixels - contentWidth;

gridview.setNumColumns(numColumns);
gridview.setPadding(slack / 2, slack / 2, slack / 2, slack / 2);

Solution 2

Set the stretch mode to columnWidth on your GridView layout or style:

android:stretchMode="columnWidth"

The column width will stretch to fill the available space. You can wrap your grid items in a transparent container that will stretch evenly while preserving the width of your visible content. The android:columnWidth attribute will function as "minimum column width." This also works with android:numColumns=auto_fit, android:horizontalSpacing and android:verticalSpacing.

Depending on what your grid items are you may not want to add a transparent container around your content. If you don't, the content width will stretch evenly which may actually look better on more devices.

Solution 3

Have you checked that your GridView positioned properly within LinearLayout? Try yo use android:layout_gravity="center" for GridView. Also, experiment with android:gravity= and different position to get more clear view on how gravity works for layouts.

Solution 4

Probably I am really late, but if you came to this question (as I did), this is what I've done to solve the problem:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/emotions_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"/>

    <GridView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>
</RelativeLayout>

My GridView is centred in the vertical, the other two TextView are on the Top and Button-Right.

More info: RelativeLayout, Positioning Views

Share:
17,731

Related videos on Youtube

Judrius
Author by

Judrius

Updated on June 04, 2022

Comments

  • Judrius
    Judrius almost 2 years

    I need to center grid view horizontally in my android layout.xml. I have searched google for quite a while but didnt succeed in finding an answer.

    I can only change gridview horizontal position by changing strechMode, but then my items are not near one another. that i need is items be one near another (without spaces) and centered horizontally. I choose strechmode = none, so now my items are near one another, but they are on the left of the screen, i just want them to be centered horizontally.

    Here is my layout xml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent"
              android:background="@drawable/background" 
              android:gravity="center">
    
    <GridView android:id="@+id/lw_gridview" 
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:numColumns="3" 
              android:columnWidth="48dp"
              android:horizontalSpacing="0dp"
              android:verticalSpacing="0dp"
              android:stretchMode="none"
              />
    
    
    </LinearLayout>
    

    Here is fragment of an image which is set on gridview by image adapter:

    imageView = new ImageView(context);
    imageView.setLayoutParams(new GridView.LayoutParams(48,48)); //on medium density
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    imageView.setPadding(0, 0, 0, 0);
    

    How can i succeed?

  • Judrius
    Judrius almost 13 years
    gravity="center" in parent makes gridview center vertically but not horizontally. gravity="center" and gravity_layout="center" in gridview makes nothing. In other components (not gridview) gravity works correctly :)
  • ACM64
    ACM64 almost 13 years
    I tell you how I did - I just added some margins (same size to center on the sceen)
  • homer_simpson
    homer_simpson almost 12 years
    The hint with the transparent container helped me a lot to get my autofit columns streched across the gridview width but not stretch the contents, so the columns are now fit perfectly in the screen and are no longer left aligned. Thanks for this James Wald.
  • YuDroid
    YuDroid almost 10 years
    How can I achieve the dynamic layout for the image shown in this link:stackoverflow.com/questions/19156385/…. Can you please guide/suggest/example for this?
  • Vignesh Sundaramoorthy
    Vignesh Sundaramoorthy over 7 years
    @YuDroid Did you achieved this how-to-cenralize-last-uneven-row-in-gridview, Is the above answer solve this?, I am having the same problem, please anyone give me a solution
  • Vignesh Sundaramoorthy
    Vignesh Sundaramoorthy over 7 years
    @PēterisCaune Is your answer solve this how-to-cenralize-last-uneven-row-in-gridview