自定义view一直是Android进阶路上的一块石头,跨过去就是垫脚石,跨不过去就是绊脚石。作为一个攻城狮,怎么能被他绊倒,一定要跟它死磕到底,这段时间看到自定义View新手实战-一步步实现精美的钟表界面特别漂亮,咱们也来手撸一个。
先看下效果图
咱们先写一个类WatchBoard继承View,并重写他的构造方法
public class WatchBoard extends View {
public WatchBoard(Context context) {
this(context,null);
}
public WatchBoard(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public WatchBoard(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr,0);
}
public WatchBoard(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
/**
* 这是最全面构造方法的写法,存在一个问题,当minSdkVersion<21的时候,这里会出现红线,这里有两个解决办法
* 1.删除最后一个构造函数,使用前三个就可以,最直接暴力。
* 2.加入 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)或者
* @TargetApi(Build.VERSION_CODES.LOLLIPOP),
* 这里注意加入这些注解只是不出现红线,一旦使用这个构造函数在API 21以下还是会出现错误。
*/
// 这里写内容
}
1. 首先声明需要的属性
在res/values包下新建attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--自定义属性-->
<declare-styleable name="WatchBoard">
<!--表盘的内边距-->
<attr name="wb_padding" format="dimension"/>
<!--表盘文字大小-->
<attr name="wb_text_size" format="dimension"/>
<!--时针的宽度-->
<attr name="wb_hour_pointer_width" format="dimension"/>
<!--分针的宽度-->
<attr name="wb_minute_pointer_width" format="dimension"/>
<!--秒针的宽度-->
<attr name="wb_second_pointer_width" format="dimension"/>
<!--指针圆角值-->
<attr name="wb_pointer_corner_radius" format="dimension"/>
<!--指针超过中心点的长度-->
<attr name="wb_pointer_end_length" format="dimension"/>
<!--时刻刻度颜色-->
<attr name="wb_scale_long_color" format="color"/>
<!--非时刻刻度颜色-->
<attr name="wb_scale_short_color" format="color"/>
<!--时针颜色-->
<attr name="wb_hour_pointer_color" format="color"/>
<!--分针颜色-->
<attr name="wb_minute_pointer_color" format="color"/>
<!--秒针颜色-->
<attr name="wb_second_pointer_color" format="color"/>
</declare-styleable>
</resources>
我们一气呵成,在类里面声明需要的属性如下
private float mRadius;