网格视图GridView是一种常见的适配器视图,用于以网格的方式显示信息
- 基本属性
xml文件中的属性 | GridView类的设置方法 | 说明 |
---|---|---|
horizontalSpacing | setHorizontalSpacing | 指定每个网格在水平方向上的间距 |
verticalSpacing | setVertcalSpacing | 指定每个网格在垂直方向上的间距 |
numColumn | setNumColumn | 设置GridView的列数,即一行有多少个网格 |
stretchMode | setStretchMode | 设置剩余空间(网格以外的空间)的拉伸模式 |
columnWidth | setColumnWidth | 设置每列的宽度 |
xml文件中的拉伸模式 | GridView类中的拉伸模式 | 说明 |
---|---|---|
none | NO_STRETCH | 不拉伸 |
columnWidth | STRETCH_COLUMN_WIDTH | 拉伸列宽填补剩余空间 |
spacingWidth | STRETCH_SPACING | 列宽不变,拉伸每列的间距填补剩余空间 |
spacingWidthUniform | STRETCH_SPACING_UNIGORM | 列宽不变,拉伸每列左右的空隙填补剩余空间 |
其中spacingWidth和spacingWidthUniform很像,spacingWidth拉伸的是两列之间的距离,不填充左右边距,而spacingWidthUniform拉伸的是每列的左右间隙,即使该列的左边或者右边没有其它的列(左右边距)
- 适配器
GridView与其他的适配器控件相差无几,实现了3个与适配器相关的方法
- setAdapter:设置数据适配器,一般继承自BaseAdapter
- setOnItemClickListener:设置网格项的点击事件监听器
- setOnItemLongClickListener:设置网格项的长按事件监听器
- 分割线
GridView提供没有设置分割线的方法,但是我们可以通过其它方法来给GridView设置分割线
方法一:设置GridView的背景色以及网格之间的水平和垂直间距,再给网格项设置与GridView不同的背景色,让GridView的背景色变成分割线的效果。
这个方法不能设置网格视图边缘的分割线,要想显示出全部的分割线,需要为GridView设置padding属性。
方法二:自定义控件,重绘GridView画出分割线。
重绘GridView,绘制指定位置分割线示例代码
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
//绘制边框
int column = getNumColumns(); //获取列数
int row = (int) Math.ceil(getChildCount() / (float) column); //获取行数
int childCount = getChildCount();
Paint linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
linePaint.setStyle(Paint.Style.STROKE);
linePaint.setColor(Color.WHITE);
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if ((i + 1) > column * (row - 1)) {
//最后一行
if ((i + 1) == column * row) {
continue;
} else {
//最后一行且不是最后一个,画右边
canvas.drawLine(child.getRight(), child.getTop(), child.getRight()
, child.getBottom(), linePaint);
}
} else if ((i + 1) % column == 0) {
//最右列,画底边
canvas.drawLine(child.getLeft(), child.getBottom(), child.getRight()
, child.getBottom(), linePaint);
} else {
//画右边和底边
canvas.drawLine(child.getLeft(), child.getBottom(), child.getRight()
, child.getBottom(), linePaint);
canvas.drawLine(child.getRight(), child.getTop(), child.getRight()
, child.getBottom(), linePaint);
}
if ((i + 1) <= column) {
//第一行,画顶边
canvas.drawLine(child.getLeft(), child.getTop(), child.getRight()
, child.getTop(), linePaint);
}
}
}