前面主要说了自定义View的一些知识,这篇文章主要是利用自定义View做一个仿小米运动计步功能的控件,如下图所示:
分析一下思路:
1.画背景
2.画一个最外部的圆
3.画圆上的小圆点
4.画竖线,环绕一周
5.画圆环
6.画文字
7.添加动画
为了可以自定义各个控件的显示效果,自定义View的属性还是必要的。
自定义属性
自定义属性主要是自定义了各个部件的颜色,format是该属性的取值类型。
这里要注意的是,自定义属性的name定义成了XiaoMiStep,那么自定义View的名字也要是XiaoMiStep,保持一致。
<declare-styleable name="XiaoMiStep">
<!--背景-->
<attr name="backGroundColor" format="color"></attr>
<!--最外层圆-->
<attr name="outerCircleColor" format="color"></attr>
<!--外层圆上的小圆点颜色-->
<attr name="outerDotColor" format="color"></attr>
<!--竖线的颜色-->
<attr name="lineColor" format="color"></attr>
<!--圆环的颜色-->
<attr name="ringColor" format="color"></attr>
<!--步数颜色-->
<attr name="stepNumColor" format="color"></attr>
<!--其他字的颜色-->
<attr name="othetTextColor" format="color"></attr>
</declare-styleable>
然后就是在布局文件中申明我们的自定义view。
这样,自定义View XiaoMiStep在xml布局文件里引用的时候,代码如下:
<com.example.ahuang.viewandgroup.view.XiaoMiStep
android:id="@+id/xiaoMiStep"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:backGroundColor="#0FA9C1"
custom:lineColor="#8ED8E5"
custom:othetTextColor="#8ED8E5"
custom:outerCircleColor="#8ED8E5"
custom:outerDotColor="#ffffff"
custom:ringColor="#8ED8E5"
custom:stepNumColor="#ffffff"/>
记得最后要引入我们的命名空间
xmlns:custom="http://schemas.android.com/apk/res-auto"
引入我们自定义的属性
获得atts.xml定义的属性值
自定义View一般需要实现一下三个构造方法,这三个构造方法是一层调用一层的,属于递进关系。因此,我们只需要在最后一个构造方法中来获得View的属性了。
- 通过theme.obtainStyledAttributes()方法获得自定义控件的主题样式数组
- 就是遍历每个属性来获得对应属性的值,也就是我们在xml布局文件中写的属性值
- 就是在循环结束之后记得调用array.recycle()来回收资源
public XiaoMiStep(Context context) {