欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android自定义View仿QQ健康界面

程序员文章站 2024-03-02 13:39:34
最近一直在学习自定义view相关的知识,今天给大家带来的是qq健康界面的实现。先看效果图: 可以设置数字颜色,字体颜色,运动步数,运动排名,运动平均步数,虚线下...

最近一直在学习自定义view相关的知识,今天给大家带来的是qq健康界面的实现。先看效果图:

Android自定义View仿QQ健康界面

可以设置数字颜色,字体颜色,运动步数,运动排名,运动平均步数,虚线下方的蓝色指示条的长度会随着平均步数改变而进行变化。整体效果还是和qq运动健康界面很像的。

自定义view四部曲,一起来看看怎么实现的。

1.自定义view的属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 //自定义属性名,定义公共属性
 <attr name="titlesize" format="dimension"></attr>
 <attr name="titletext" format="string"></attr>
 <attr name="titlecolor" format="color"></attr>
 <attr name="outcirclecolor" format="color"></attr>
 <attr name="incirclecolor" format="color"></attr>
 <attr name="linecolor" format="color"></attr>
 //自定义view的属性
 <declare-styleable name="myqqhealthview">
 <attr name="titlecolor"></attr>
 <attr name="linecolor"></attr>
 </declare-styleable>
</resources>

依次定义了字体颜色,线的颜色2个属性,format是该属性的取值类型。
然后就是在布局文件中申明我们的自定义view:

 <com.example.tangyangkai.myview.myqqhealthview
  android:id="@+id/myqqview"
  android:layout_width="match_parent"
  android:layout_height="530dp"
  android:layout_margin="15dp"
  myqq:linecolor="@color/font_tips"
  myqq:titlecolor="@color/textcolor"
  myqq:titlesize="50dp" />

自定义view的属性我们可以自己进行设置,记得最后要引入我们的命名空间,
xmlns:app=”http://schemas.android.com/apk/res-auto”

2.获取自定义view的属性:

 public myqqhealthview(context context) {
 this(context, null);
 }

 public myqqhealthview(context context, attributeset attrs) {
 this(context, attrs, 0);
 }

 public myqqhealthview(context context, attributeset attrs, int defstyleattr) {
 super(context, attrs, defstyleattr);

 //获取我们自定义的样式属性
 typedarray array = context.gettheme().obtainstyledattributes(attrs, r.styleable.myqqhealthview, defstyleattr, 0);
 int n = array.getindexcount();
 for (int i = 0; i < n; i++) {
  int attr = array.getindex(i);
  switch (attr) {
  case r.styleable.myqqhealthview_titlecolor:
   // 默认颜色设置为黑色
   textcolor = array.getcolor(attr, color.black);
   break;
  case r.styleable.myqqhealthview_linecolor:
   linecolor = array.getcolor(attr, color.black);
   break;
  }

 }
 array.recycle();
 init();
 }

自定义view一般需要实现一下三个构造方法,这三个构造方法是一层调用一层的,属于递进关系。因此,我们只需要在最后一个构造方法中来获得view的属性了。

第一步通过theme.obtainstyledattributes()方法获得自定义控件的主题样式数组;
第二步就是遍历每个属性来获得对应属性的值,也就是我们在xml布局文件中写的属性值;
第三步就是在循环结束之后记得调用array.recycle()来回收资源;
第四步就是进行一下必要的初始化,不建议在ondraw的过程中去实例化对象,因为这是一个频繁重复执行的过程,new是需要分配内存空间的,如果在一个频繁重复的过程中去大量地new对象会造成内存浪费的情况。

3.重写onmesure方法确定view大小:
当你没有重写onmeasure方法时候,系统调用默认的onmeasure方法:

@override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 super.onmeasure(widthmeasurespec, heightmeasurespec);
 }

这个方法的作用是:测量控件的大小。其实android系统在加载布局的时候是由系统测量各子view的大小来告诉父view我需要占多大空间,然后父view会根据自己的大小来决定分配多大空间给子view。measurespec的specmode模式一共有三种:

measurespec.exactly:父视图希望子视图的大小是specsize中指定的大小;一般是设置了明确的值或者是match_parent
measurespec.at_most:子视图的大小最多是specsize中的大小;表示子布局限制在一个最大值内,一般为warp_content
measurespec.unspecified:父视图不对子视图施加任何限制,子视图可以得到任意想要的大小;表示子布局想要多大就多大,很少使用。

想要设置warp_content,只要重写onmeasure方法:

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
 int widthmode = measurespec.getmode(widthmeasurespec);
 int widthsize = measurespec.getsize(widthmeasurespec);
 int heightmode = measurespec.getmode(heightmeasurespec);
 int heightsize = measurespec.getsize(heightmeasurespec);
 int width;
 int height;
 //如果布局里面设置的是固定值,这里取布局里面的固定值;如果设置的是match_parent,则取父布局的大小
 if (widthmode == measurespec.exactly) {
  width = widthsize;
 } else {

  //如果布局里面没有设置固定值,这里取布局的宽度的1/2
  width = widthsize * 1 / 2;
 }

 if (heightmode == measurespec.exactly) {
  height = heightsize;
 } else {
  //如果布局里面没有设置固定值,这里取布局的高度的3/4
  height = heightsize * 3 / 4;
 }
 widthbg = width;
 heightbg = height;
 setmeasureddimension(width, height);
 startanim();
 }

我这里为了不让布局显得过小,所以warp_content分别取宽的1/2,高的3/4,具体情况因人而异。

4.重写ondraw方法进行绘画:
界面比较复杂,我们从上到下,一步一步来:

 //绘制最底层的背景
 radiusbg = widthbg / 20;
 pathbg.moveto(0, heightbg);
 pathbg.lineto(0, radiusbg);
 pathbg.quadto(0, 0, radiusbg, 0);
 pathbg.lineto(widthbg - radiusbg, 0);
 pathbg.quadto(widthbg, 0, widthbg, radiusbg);
 pathbg.lineto(widthbg, heightbg);
 pathbg.lineto(0, heightbg);
 backgroundpaint.setcolor(color.white);
 canvas.drawpath(pathbg, backgroundpaint);

整个自定义view的最底层是一个左上,右上有弧度,左下,右下为直角的白色背景。使用canvas.drawroundrect实现的矩形是四个角都有弧度,达不到预期。但是一阶贝塞尔曲线加上二阶贝塞尔曲线就能很好的实现这种特殊的情况。
moveto(x,y):不会进行绘制,只用于移动移动画笔,确定起点坐标,与其他方法配合使用;
lineto(x,y):一阶贝塞尔曲线,坐标为终点坐标,配合moveto方法用于进行直线绘制;
quadto (x1,y1,x2,y2):二阶贝塞尔曲线,(x1,y1) 为控制点,(x2,y2)为结束点,用于绘制圆滑的曲线;
最后调用canvas.drawpath(path,paint)即可达到这种效果

 //绘制圆弧
 arcpaint.setstrokewidth(widthbg / 20);
 //设置空心
 arcpaint.setstyle(paint.style.stroke);
 //防抖动
 arcpaint.setdither(true);
 //连接处为圆弧
 arcpaint.setstrokejoin(paint.join.round);
 //画笔的笔触为圆角
 arcpaint.setstrokecap(paint.cap.round);
 arcpaint.setcolor(linecolor);
 //圆弧范围
 arcrect = new rectf(widthbg * 1 / 4, widthbg * 1 / 4, widthbg * 3 / 4, widthbg * 3 / 4);
 //绘制背景大圆弧
 canvas.drawarc(arcrect, 120, 300, false, arcpaint);
 arcpaint.setcolor(textcolor);
 //绘制分数小圆弧
 canvas.drawarc(arcrect, 120, arcnum, false, arcpaint);

绘制圆弧先确定圆弧的范围,传入的四个参数就是圆弧所在圆的外接矩形的坐标。canvas.drawarc的五个参数依次是圆弧范围;开始的角度;圆弧的角度;第四个为true时,在绘制圆弧时会将圆心包括在内,通常用来绘制扇形,我们这里选false;圆弧的画笔

 //绘制圆圈内的数字
 textpaint.setcolor(textcolor);
 textpaint.settextsize(widthbg / 10);
 canvas.drawtext(string.valueof(walknum), widthbg * 3 / 8, widthbg * 1 / 2 + 20, textpaint);
 //绘制名次
 textpaint.settextsize(widthbg / 15);
 canvas.drawtext(string.valueof(ranknum), widthbg * 1 / 2 - 15, widthbg * 3 / 4 + 10, textpaint);

 //绘制其他文字
 textpaint.setcolor(linecolor);
 textpaint.settextsize(widthbg / 25);
 canvas.drawtext("截止13:45已走", widthbg * 3 / 8 - 10, widthbg * 5 / 12 - 10, textpaint);
 canvas.drawtext("好友平均2781步", widthbg * 3 / 8 - 10, widthbg * 2 / 3 - 20, textpaint);
 canvas.drawtext("第", widthbg * 1 / 2 - 50, widthbg * 3 / 4 + 10, textpaint);
 canvas.drawtext("名", widthbg * 1 / 2 + 30, widthbg * 3 / 4 + 10, textpaint);

 //绘制圆圈外的文字
 canvas.drawtext("最近7天", widthbg * 1 / 15, widthbg, textpaint);
 myaveragetxt = string.valueof(averagesize);
 canvas.drawtext("平均", widthbg * 10 / 15 - 15, widthbg, textpaint);
 canvas.drawtext(myaveragetxt, widthbg * 11 / 15, widthbg, textpaint);
 canvas.drawtext("步/天", widthbg * 12 / 15 + 20, widthbg, textpaint);

绘制文字就稍微简单点,这里计算好各自的位置即可

 //绘制虚线
 linepaint.setstyle(paint.style.stroke);
 linepaint.setstrokewidth(2);
 linepaint.setcolor(linecolor);
 linepath.moveto(widthbg * 1 / 15, widthbg + 80);
 linepath.lineto(widthbg * 14 / 15, widthbg + 80);
 linepaint.setpatheffect(effects);
 canvas.drawpath(linepath, linepaint);

 rectsize = widthbg / 12;
 rectagheight = widthbg / 10;
 //绘制虚线上的圆角竖线
 for (int i = 0; i < fouractivity.sizes.size(); i++) {
  rectpaint.setstrokewidth(widthbg / 25);
  rectpaint.setstyle(paint.style.stroke);
  rectpaint.setstrokejoin(paint.join.round);
  rectpaint.setstrokecap(paint.cap.round);
  float startheight = widthbg + 90 + rectagheight;
  rectpath.moveto(rectsize, startheight);
  double percentage = double.valueof(fouractivity.sizes.get(i)) / double.valueof(averagesize);
  double height = percentage * rectagheight;
  rectpath.lineto(rectsize, (float) (startheight - height));
  rectpaint.setcolor(textcolor);
  canvas.drawpath(rectpath, rectpaint);
  //绘制下方的文字
  textpaint.setcolor(linecolor);
  canvas.drawtext("0" + (i + 1) + "日", rectsize - 25, startheight + 50, textpaint);
  rectsize += widthbg / 7;
 }

dashpatheffect的作用就是将path的线段虚线化。构造函数为dashpatheffect(float[] intervals, float offset),其中intervals为虚线的on和off数组,该数组的length必须大于等于2,float[0] ,float[1] 依次代表第一条实线与第一条虚线的长度,如果数组后面不再有数据则重复第一个数以此往复循环。offset为绘制时的偏移量。

dashpatheffect effects = new dashpatheffect(new float[]{5,5}, 1);

然后将这个实例作为linepaint.setpatheffect()的参数即可。绘制下方文字写的是一个简单的循环,然后竖线的长度是根据步数数组大小来进行计算的。示例图中改变平均步数以后,竖线的长度也进行了变化。

 //绘制底部波纹
 weavpaint.setcolor(textcolor);
 weavpath.moveto(0, heightbg);
 weavpath.lineto(0, heightbg * 10 / 12);
 weavpath.cubicto(widthbg * 1 / 10, heightbg * 10 / 12, widthbg * 3 / 10, heightbg * 11 / 12, widthbg, heightbg * 10 / 12);
 weavpath.lineto(widthbg, heightbg);
 weavpath.lineto(0, heightbg);
 canvas.drawpath(weavpath, weavpaint);

 //绘制底部文字
 weavpaint.setcolor(color.white);
 weavpaint.settextsize(widthbg / 20);
 canvas.drawtext("成绩不错,继续努力哟!", widthbg * 1 / 10 - 20, heightbg * 11 / 12 + 50, weavpaint);

底部水波纹的实现使用的是三阶贝塞尔曲线:
cubicto(x1, y1, x2, y2, x3, y3):三阶贝塞尔曲线, (x1,y1) 为控制点,(x2,y2)为控制点,(x3,y3) 为结束点,用于绘制复杂的曲线。

关于重写ondraw方法,个人建议就是最好在本子上将需要完成的自定义view大致轮廓画下来,标注好坐标与位置,计算一下高宽。然后根据绘制的自定义view,从上到下,从外到内,一步一步进行绘制。真的很实用,这样逻辑清晰,层次分明,对你写代码很有帮助。

5.动画的实现:

 private void startanim() {
 //步数动画的实现
 valueanimator walkanimator = valueanimator.ofint(0, mysize);
 walkanimator.addupdatelistener(new valueanimator.animatorupdatelistener() {
  @override
  public void onanimationupdate(valueanimator animation) {
  walknum = (int) animation.getanimatedvalue();
  postinvalidate();
  }
 });
 //排名动画的实现
 valueanimator rankanimator = valueanimator.ofint(0, rank);
 rankanimator.addupdatelistener(new valueanimator.animatorupdatelistener() {
  @override
  public void onanimationupdate(valueanimator animation) {
  ranknum = (int) animation.getanimatedvalue();
  postinvalidate();
  }
 });

 double size = mysize;
 double avgsize = averagesize;
 if (size > avgsize) {
  size = avgsize;
 }
 //圆弧动画的实现
 valueanimator arcanimator = valueanimator.offloat(0, (float) (size / avgsize * 300));
 arcanimator.addupdatelistener(new valueanimator.animatorupdatelistener() {
  @override
  public void onanimationupdate(valueanimator animation) {
  arcnum = (float) animation.getanimatedvalue();
  postinvalidate();
  }
 });
 animset.setduration(3000);
 animset.playtogether(walkanimator, rankanimator, arcanimator);
 animset.start();
 }

这里就不得不提到属性动画的优越性了,不仅可以作用在view上,也可以作用于某个对象上。只需要设置好开始值与结束值,添加一个动画的监听,就能够得到变化的值,再使用postinvalidate()方法,从而调用ondraw方法来进行数值的改变。最后设置一个组合动画—-animatorset,使三个动画达到同步一致的效果。
然后就是使用动画了,刚开始我是将这个方法写在init()初始化函数里面,一直达不到预期的效果。后来才知道,自定义view进行初始化的时候,组合动画需要的一些值:步数,排名,平均步数等还没有传递过来,所以动画无法完成。最后我是将这个方法写在onmeasure()方法的后面才达到效果,这里很感谢同事的提醒。

6.设置步数大小以及在activity中的使用:

 public void reset(int mysize, int myrank, int myaveragesize) {
 walknum = 0;
 arcnum = 0;
 ranknum = 0;
 mysize = mysize;
 rank = myrank;
 averagesize = myaveragesize;
 startanim();
 }

将设置的值通过构造方法传递过来,最后调用开启动画的方法即可。对应的activity的代码:

public class fouractivity extends appcompatactivity {

 private myqqhealthview view;
 public static list<integer> sizes = new arraylist<>();
 private button btn;
 @override
 protected void oncreate(bundle savedinstancestate) {
 super.oncreate(savedinstancestate);
 setcontentview(r.layout.activity_four);
 initview();
 }

 private void initview() {
 view = (myqqhealthview) findviewbyid(r.id.myqqview);
 view.setmysize(2345);
 view.setrank(11);
 view.setaveragesize(5436);
 sizes.add(1234);
 sizes.add(2234);
 sizes.add(4234);
 sizes.add(6234);
 sizes.add(3834);
 sizes.add(7234);
 sizes.add(5436);
 btn = (button) findviewbyid(r.id.set_btn);
 btn.setonclicklistener(new view.onclicklistener() {
  @override
  public void onclick(view v) {
  view.reset(6534, 8, 4567);
  }
 });
 }
}

自己根据情况设置想要的值就可以了。

整个流程走下来,你会发现其实自定义view并没有想象之中的那么难。多加练习,熟能生巧,相信再复杂的界面也难不住我们的。

ok,下一篇自定义view再见。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。