Android 给GridView添加分割线

来源:互联网 发布:当淘宝模特工资多少 编辑:程序博客网 时间:2024/06/05 18:57

GridView添加分割线,只要重写dispatchDraw方法来进行绘制;

首先看一下效果图


代码如下:


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.grey));        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);            }        }    }