1.自定义view的属性
(1)自定义属性:在res/values/新建一个attrs.xml文件里面定义需要的属性;
<resources>
<declare-styleable name="SolarView">
<attr name="max"/>
<attr name="pregress" format="integer" />
<attr name="color" format="color" />
<attr name="solarScale" format="float" />
<attr name="lightRadius" format="dimension" />
</declare-styleable>
</resources>
在布局中声明我们自定义的View:
<com.iezview.mus3d.view.SolarView
android:id="@+id/sv_light"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:color="@color/white"
app:lightRadius="2dp"
app:max="8"
app:pregress="3"
app:solarScale="0.26" />
一定要引入 xmlns:custom="http://schemas.android.com/apk/res/包名"我们的命名空间,后面的包路径指的是项目的package
(2)在View的构造函数中获取相关的属性
private void init(AttributeSet attrs, int defStyle) {
//获取定义的相关属性
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.SolarView, defStyle, 0);
mColor = a.getColor(R.styleable.SolarView_color, Color.RED);
mMax = a.getInt(R.styleable.SolarView_max, 9);
mPregress = a.getInt(R.styleable.SolarView_pregress, 0);
mLolarScale = a.getFloat(R.styleable.SolarView_solarScale, 0.25F);
mLightRadius = a.getDimensionPixelSize(R.styleable.SolarView_lightRadius, 10);
mLightRadiusAnim = mLightRadius;
a.recycle();
//初始化画笔
initPaint();
//初始化相关动画
initAnim();
}
我们重写了3个构造方法,默认的布局文件调用的是两个参数的构造方法,所以记得让所有的构造调用我们的三个参数的构造,我们在三个参数的构造中获得自定义属性。
3.重写onMesure()方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
int w = resolveSizeAndState(minw, widthMeasureSpec, 0);
int minh = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
int h = resolveSizeAndState(minh, heightMeasureSpec, 0);
setMeasuredDimension(w, h);
}
4.重写onDraw()方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//实心圆,直径为控件的最小宽高的一半
int min = Math.min(getWidth(), getHeight());
float r = min * mLolarScale;
mPaint.setColor(mColor);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, r, mPaint);
for (int i = 0; i < mMax && i < mPregress; i++) {
canvas.save();
canvas.rotate((360f / mMax) * i, getWidth() >> 1, getHeight() >> 1);
if (i == mPregress - 1) {
canvas.drawCircle(getWidth() >> 1, getHeight() >> 3, mLightRadiusAnim, mPaint);
} else {
canvas.drawCircle(getWidth() >> 1, getHeight() >> 3, mLightRadius, mPaint);
}
canvas.restore();
}
}