android GridView添加分割线

网上找了些资料 感觉写的好麻烦  于是按自己的想法写了一个   同样思路也可以再recyclerview之类的用

public class AutoHeightGridView extends GridView {
    private int itemNum;
    public AutoHeightGridView(Context context) {
        super(context);
    }

    public AutoHeightGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoHeightGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        View localView1 = getChildAt(0);
        if(null == localView1){
            return;
        }
        int column = getWidth() / localView1.getWidth();//计算出一共有多少列,
        int childCount = getChildCount();//view的总数
        System.out.println("view的总数childCount==" + childCount);
        Paint localPaint;//画笔
        localPaint = new Paint();
        localPaint.setTextSize(2);
        localPaint.setStyle(Paint.Style.STROKE);
//        localPaint.setColor(getContext().getResources().getColor(R.color.light_black));//设置画笔的颜色
        localPaint.setColor(Color.parseColor("#C8C8C8"));//设置画笔的颜色
        for (int i = 0; i < childCount; i++) {//遍历子view
            View cellView = getChildAt(i);//获取子view
            if((i+1)%column != 0){//不是最后一个就画底部和右侧的线
                canvas.drawLine(cellView.getLeft(), cellView.getBottom()-(float) Math.floor(i/column), cellView.getRight(), cellView.getBottom()-(float) Math.floor(i/column), localPaint);
                canvas.drawLine(cellView.getRight(), cellView.getBottom(), cellView.getRight(), cellView.getTop(), localPaint);
            }else{
                canvas.drawLine(cellView.getLeft(), cellView.getBottom()-(float) (i/column), cellView.getRight(), cellView.getBottom()-(float) Math.floor(i/column), localPaint);
            }
        }
    }
}

直接在需要用的地方引用

<com.holly.common_view.view.AutoHeightGridView
    android:id="@+id/gv_content"
    android:numColumns="2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:listSelector="@null"
    android:horizontalSpacing="0dp"
    android:verticalSpacing="0dp"
   />
最后自己在适配器的item中加个点击效果就好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值