自定义控件在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));
}
然后就完成了。。。。