get horizontal and vertical spacing in gridview

15,797

Solution 1

You can use android:verticalSpacing and android:horizontalSpacing in GridView tag and provide the spacing as per your requirement.

For example:

<GridView
    android:layout_height="wrap_content"
    android:id="@+id/gridView1"
    android:layout_width="match_parent"
    android:numColumns="auto_fit"
    android:horizontalSpacing="10dp"       // space between two items (horizontal)
    android:verticalSpacing="10dp">        // space between two rows (vertical)

On java try:

"gridviewname".getHorizontalSpacing()
"gridviewname".getVerticalSpacing()

Solution 2

You can also try in Java

mGridView.setHorizontalSpacing(4);
mGridView.setVerticalSpacing(4);

Or in XML

<GridView
    android:layout_height="wrap_content"
    android:id="@+id/gridView1"
    android:layout_width="match_parent"
    android:numColumns="auto_fit"
    android:horizontalSpacing="4dp"  
    android:verticalSpacing="4dp">

Solution 3

If your minSdk is 16 then you can use mGridView.getHorizontalSpacing() or mGridView.getVerticalSpacing().

If not, you can set in the xml layout android:verticalSpacing="@dimen/grid_spacing" and in the code use getResources().getDimensionPixelSize(R.dimen.grid_spacing).

This way, you can change the size in just one place and it'll effect both the xml-layout and the code.

Inside /res/values/dimens.xml add this line -

<dimen name="grid_spacing">10dp</dimen>
Share:
15,797
dd619
Author by

dd619

Updated on June 13, 2022

Comments

  • dd619
    dd619 about 2 years

    I am implementing a grid view in my application and I want to get the horizontal spacing between consecutive rows and vertical spacing between consecutive columns within grid view using java code.

    Is it possible? Is there any direct methods to get spacing?