一:自定义属性
在values文件夹下,打开attrs.xml,其实这个文件名称可以是任意的,写在这里更规范一点,表示里面放的全是view的属性<注意format类型>
<resources>
<declare-styleable name="rainbow">
<attr name="rainbow_hspace" format="dimension">attr>
<attr name="rainbow_wspace" format="dimension">attr>
<attr name="rainbow_color" format="color">attr>
declare-styleable>
resources>
二:继承自View
package com.tool.keyproject;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class KeyView extends View {
int barColor = Color.parseColor("#1E88E5");
int hSpace = 50;
int vSpace = 100;
int space = 20;
float delta = 10f;
private Paint paint;
float startX = 0;
public KeyView(Context context) {
super(context);
}
public KeyView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public KeyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.rainbow, 0, 0);
hSpace = typedArray.getDimensionPixelSize(R.styleable.rainbow_rainbow_hspace, hSpace);
vSpace = typedArray.getDimensionPixelOffset(R.styleable.rainbow_rainbow_wspace, vSpace);
barColor = typedArray.getColor(R.styleable.rainbow_rainbow_color, barColor);
paint = new Paint();
paint.setColor(barColor);
paint.setAntiAlias(true);
paint.setStrokeWidth(space);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float sw = this.getMeasuredWidth();
if (startX >= sw + (hSpace + space) - (sw % (hSpace + space))) {
startX = 0;
} else {
startX += delta;
}
float start = startX;
while (start < sw) {
canvas.drawLine(start, 5, start + hSpace, 5, paint);
start += (hSpace + space);
}
start = startX - space - hSpace;
while (start >= -hSpace) {
canvas.drawLine(start, 5, start + hSpace, 5, paint);
start -= (hSpace + space);
}
invalidate();
}
}
三:布局文件引用
<com.tool.keyproject.KeyView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:rainbow_color="@android:color/holo_blue_bright"
app:rainbow_hspace="80dp"
app:rainbow_wspace="10dp"
>com.tool.keyproject.KeyView>