自定义View的相关文章:
- Android 实现一个简单的自定义View
- Android 自定义View步骤
- Android Paint详解
- Android 自定义View之Canvas相关方法说明
- Android 自定义View实例之 “京东跑”
- Android 自定义View实例之进度圆环
- Android 源码分析(TextView)
- Android 自定义View分发流程
- Android 自定义View 需要注意的事项
我们实现这样一个自定义View,绘制一个圆,半径和颜色可以通过属性设置。
public class MyView extends View {
/**
* 圆的半径,默认画出最大圆
*/
private float radius;
/**
* 圆的颜色
*/
private int color;
private Paint mPaint;
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
//获取设置的属性值
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyView);
radius = typedArray.getDimension(R.styleable.MyView_radius, 0);
color = typedArray.getColor(R.styleable.MyView_android_color, Color.RED);
typedArray.recycle();
//初始化Paint
mPaint = new Paint();
mPaint.setColor(color);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//计算半径,如果属性中设置了半径则使用设置的值,否则是宽和高一半的较小值
float mRadius = radius == 0 ? Math.min(getWidth() / 2, getHeight() / 2) : radius;
//绘制圆
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mRadius, mPaint);
}
}
在res/values目录下创建attrs.xml,这里面我们定义了我们需要的属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="radius" format="dimension"></attr>
<attr name="android:color"/>
</declare-styleable>
</resources>
使用:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="qiwei.com.frameworknote.ui.MainActivity">
<qiwei.com.frameworknote.ui.MyView
android:layout_width="100dp"
android:layout_height="100dp"
app:radius="20dp"
android:color="@color/colorPrimaryDark"/>
</android.support.constraint.ConstraintLayout>
所以自定义View实现的步骤:
- 创建View并继承View
- 设置View属性
- 获取View属性值
- 初始化Paint(Paint用于绘制)
- 重写onMesure方法,不是必须的,此View未写,后面会详细介绍
重写onDraw方法
自定义View重点在onDraw方法,这个方法里面我们要绘制出界面下一篇文章我们会详细的介绍各个步骤。