最简单的自定义View,画一个圆。
自定义的意义:现有的不能满足需求,所以我们自己来实现我们的需求。
- 自定义圆需要设定一些属性,如圆的颜色,圆的的宽度。在Value下面新建一个attrs的xml文件,
name后面跟的上是我们自定义的属性标签 format是告诉系统这个标签是来做什么的
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Circle">
<attr name="circle_Color" format="color"></attr>
<attr name="cirlce_Width" format="dimension"></attr>
</declare-styleable>
</resources>
- 继承一个View,实现其构造方法,在构造方法里获得自定义属性值
public CirlcleView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
//1.获得自定义属性值的一个容器
TypedArray mTd = context.obtainStyledAttributes(attrs, R.styleable.Circle);
//2.通过属性容器获得属性,如果没有就使用默认值
roundColor = mTd.getColor(R.styleable.Circle_circle_Color, Color.GREEN);
roundWidth = mTd.getDimension(R.styleable.Circle_cirlce_Width, 5);
//3.释放重复利用
mTd.recycle();
}
3.在onDraw方法里进行圆的绘制
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/*
* 画一个圆
* 1. 需要有圆心坐标
* 2. 需要有半径
*/
int center = getWidth()/2; //圆心x坐标
int radius = (int) (center-roundWidth/2); //圆环的半径
//设置圆的各项属性
paint.setColor(roundColor);
paint.setStyle(Paint.Style.STROKE); //空心
paint.setStrokeWidth(roundWidth); //圆环的宽度
paint.setAntiAlias(true); //抗锯齿
canvas.drawCircle(center, center, radius, paint); //绘制圆
}
4.在xml里进行使用,这里一定要引入自定义的属性,在最顶层布局里面加入 xmlns:app=”http://schemas.android.com/apk/res-auto”就可以了,红色部分是自己可以写的,意思就是通过app这个标签,可以找到我们要使用的属性空间
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.example.circle.CirlcleView
android:id="@+id/circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
app:circle_Color="#000000"
app:cirlce_Width="10dp" />
</RelativeLayout>