自定义控件在LinearLayout上面绘制一条线

自定义控件在LinearLayout上面绘制一条线

前言
这篇博客是这样的公司项目,在列表上面用一条线把头像全部连接起来做成那种时间轴的形式。大概的话我就画一个图。
在这里插入图片描述
然后干脆就用自定义的控件来做,这个地方也就记录一下这个自定义的控件。


首先我们要明确步骤
1.从样子上面来看我们直接继承LinerLayout
2.然后在画出这更线
3.然后在给点自定义的属性


public class MyLineLayoutView extends LinearLayout {
    public MyLineLayoutView(Context context) {
        super(context);
    }

    public MyLineLayoutView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyLineLayoutView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

接下来我们就开始搞个画笔

		paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(lineColor);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(lineWidth);

然后再接下来就是测量我们直接取子控件的高度来作为这个线的长度因为里面可能会很多控件所以便利一下拿到所有子控件的高度。

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        layoutH = 0;
        int childCount = this.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = this.getChildAt(i);
            int ch = child.getMeasuredHeight();
            layoutH += ch;
        }
    }

接下来就是画了,画很简单的就是画一个线,线的高度我们之前已经计算好了

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        MyLoge.addLoge("onDraw",lineMarginBottom+"   "+layoutH);
        canvas.drawLine(linePaddingLeft,0,linePaddingLeft,(layoutH - lineMarginBottom),paint);
    }

然后就搞定了。。。。
后面就是加点自定义的属性

<declare-styleable name="LineLinearLayout">
        <attr name="padding_left" format="integer" />
        <attr name="line_width" format="integer" />
        <attr name="line_color" format="color|reference" />
    </declare-styleable>

然后在引用这些自定义的属性

private void initAttrs(AttributeSet attrs) {
        TintTypedArray tta = TintTypedArray.obtainStyledAttributes(getContext(), attrs,
                R.styleable.LineLinearLayout);
        lineColor = tta.getColor(R.styleable.LineLinearLayout_line_color,0xff000000);
        linePaddingLeft = PxtoDpUntils.dp2pxInt(context,tta.getInteger(R.styleable.LineLinearLayout_padding_left, 20));
        lineWidth = PxtoDpUntils.dp2pxInt(context,tta.getInteger(R.styleable.LineLinearLayout_line_width, 1));
    }

然后就完成了。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值