参考自:如何给gridview的单元格加上分割线 - 泡在网上的日子
效果:
方法是自定义gridview,主要是重写了gridview的dispatchDraw()方法。
因为自己的需求没有要太多的改动,基本照搬参考的代码。只不过由于ScollView和GridView的冲突问题,额外重写了onMeasure()方法。
public class LineGridView extends GridView{
public LineGridView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public LineGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LineGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void dispatchDraw(Canvas canvas){
super.dispatchDraw(canvas);
View localView1 = getChildAt(0);
int column = getWidth() / localView1.getWidth();
int childCount = getChildCount();
Paint localPaint;
localPaint = new Paint();
localPaint.setStyle(Paint.Style.STROKE);
localPaint.setColor(getContext().getResources().getColor(R.color.grid_line));
for(int i = 0;i < childCount;i++){
View cellView = getChildAt(i);
if((i + 1) % column == 0){
canvas.drawLine(cellView.getLeft(), cellView.getBottom(), cellView.getRight(), cellView.getBottom(), localPaint);
}else if((i + 1) > (childCount - (childCount % column))){
canvas.drawLine(cellView.getRight(), cellView.getTop(), cellView.getRight(), cellView.getBottom(), localPaint);
}else{
canvas.drawLine(cellView.getRight(), cellView.getTop(), cellView.getRight(), cellView.getBottom(), localPaint);
canvas.drawLine(cellView.getLeft(), cellView.getBottom(), cellView.getRight(), cellView.getBottom(), localPaint);
}
}
if(childCount % column != 0){
for(int j = 0 ;j < (column-childCount % column) ; j++){
View lastView = getChildAt(childCount - 1);
canvas.drawLine(lastView.getRight() + lastView.getWidth() * j, lastView.getTop(), lastView.getRight() + lastView.getWidth()* j, lastView.getBottom(), localPaint);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //重写防止与ScollView冲突
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);}
}
当GridView嵌套在ScrollView里,因为两者都有滚动条,会产生冲突导致无法滚动的问题。
此处的解决方法是重写GridView的onMeasure()方法,使其整体显示,不再出现滚动条,从而让ScrollView可以正常滚动。