为Gridview添加间隔线有多种方法,这里使用了自定义Gridview方法,重写dispatchDraw 方法,通过Paint来重新绘制界面。直接上代码:
importandroid.annotation.SuppressLint;
importandroid.content.Context;
importandroid.graphics.Canvas;
importandroid.graphics.Paint;
importandroid.util.AttributeSet;
importandroid.util.Log;
importandroid.view.View;
importcom.example.psa.yidongguigu.R;
importin.srain.cube.views.GridViewWithHeaderAndFooter;
@SuppressLint("NewApi")
public classMyGridView2extendsGridViewWithHeaderAndFooter {
public interfaceOnGridScroll2TopListener {
voidscroll2Top();
}
privateOnGridScroll2TopListenerlistener;
public voidsetOnGridScroll2TopListener(OnGridScroll2TopListener listener) {
this.listener= listener;
}
@Override
protected booleanoverScrollBy(intdeltaX, intdeltaY, intscrollX,
intscrollY, intscrollRangeX, intscrollRangeY,
intmaxOverScrollX, intmaxOverScrollY, booleanisTouchEvent) {
if(listener!=null) {
listener.scroll2Top();
}
return super.overScrollBy(deltaX,deltaY,scrollX,scrollY,scrollRangeX,
scrollRangeY,maxOverScrollX,maxOverScrollY,isTouchEvent);
}
@Override
protected voidonScrollChanged(intl, intt, intoldl, intoldt) {
super.onScrollChanged(l,t,oldl,oldt);
Log.e("MyListView"," t: "+ t
+" oldt: "+ oldt +": "+
getScrollY());
}
publicMyGridView2(Context context,AttributeSet attrs) {
super(context,attrs);
}
@Override
protected voidonMeasure(intwidthMeasureSpec, intheightMeasureSpec) {
intexpandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE>>2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec,expandSpec);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
View localView1 = getChildAt(0);
intcolumn = getWidth() / localView1.getWidth();
Log.i("MyGridView2","column="+ column);
intchildCount = getChildCount();
Paint localPaint;
localPaint =newPaint();
localPaint.setStyle(Paint.Style.STROKE);
localPaint.setColor(getContext().getResources().getColor(R.color.subscribe_seperate_line));
for(inti =0;i < childCount;i++) {
View cellView = getChildAt(i);
//顶部线,坐标+1是为了画在cellView上
canvas.drawLine(cellView.getLeft(),cellView.getTop(),cellView.getRight(),cellView.getTop(),localPaint);
//左边线
canvas.drawLine(cellView.getLeft(),cellView.getTop(),cellView.getLeft(),cellView.getBottom(),localPaint);
if((i +1) % column ==0)//最右边一列单元格画上右边线
{
canvas.drawLine(cellView.getRight(),cellView.getTop(),cellView.getRight(),cellView.getBottom(),localPaint);
}
if((i + column) >= childCount)//最后column个单元格画上底边线
{
Log.i("MyGridView2","画底边线");
canvas.drawLine(cellView.getLeft(),cellView.getBottom(),cellView.getRight(),cellView.getBottom(),localPaint);
}
if(childCount % column !=0&& i == childCount -1)//如果最后一个单元格不在最右一列,单独为它画上右边线
{
canvas.drawLine(cellView.getRight(),cellView.getTop(),cellView.getRight(),cellView.getBottom(),localPaint);
}
}
}
}