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