【发布时间】:2018-09-12 13:44:43
【问题描述】:
我正在我的应用程序中实现一个网格视图,我想使用 java 代码获取网格视图中连续行之间的水平间距和连续列之间的垂直间距。
有可能吗? 有没有直接获取间距的方法?
【问题讨论】:
我正在我的应用程序中实现一个网格视图,我想使用 java 代码获取网格视图中连续行之间的水平间距和连续列之间的垂直间距。
有可能吗? 有没有直接获取间距的方法?
【问题讨论】:
您可以在GridView 标签中使用android:verticalSpacing 和android:horizontalSpacing,并根据您的要求提供间距。
例如:
<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)
在java上试试:
"gridviewname".getHorizontalSpacing()
"gridviewname".getVerticalSpacing()
【讨论】:
你也可以用Java试试
mGridView.setHorizontalSpacing(4);
mGridView.setVerticalSpacing(4);
或者在 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">
【讨论】:
如果您的 minSdk 为 16,那么您可以使用 mGridView.getHorizontalSpacing() 或 mGridView.getVerticalSpacing()。
如果没有,可以在xml布局中设置android:verticalSpacing="@dimen/grid_spacing",在代码中使用getResources().getDimensionPixelSize(R.dimen.grid_spacing)。
这样,您可以只在一个地方更改大小,它会影响 xml 布局和代码。
在/res/values/dimens.xml里面添加这一行——
<dimen name="grid_spacing">10dp</dimen>
【讨论】: