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?
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()
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">
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With