1、为什么需要自定义view

android系统内置的view不满足我们的业务需求

2、自定义view的基本方法

  • onmeasure:决定着view的大小
  • onlayout:决定view在viewgroup中的位置
  • ondraw:决定绘制什么样的view

通常情况下:

  • 自定义view只需要重写onmeasure和ondraw这两个方法
  • 自定义viewgroup只需要重写onmeasure和onlayout这两个方法

3、自定义view的属性如何操作

在values文件中创建attr文件,然后使用< declare-styleable >为自定义view添加属性,在xml中设置相应的属性值,然后再自定义view的构造方法中获取属性值(atrributeset),将获取到的属性值应用到view中去

4、view的视图结构

  • 1、每一个activity都有一个window,window用于显示我们的界面,activity负责管理window
  • 2、每个window都有一个根view->decorview,window本身不能显示界面,需要依托于view
  • 3、decorview是一个framelayout,它主要由两部分组成,一部分是actionbar,一部分是一个id为android.r.content的framelayout,我们写好的activity的根部局的view就是被添加到这里去了,通过setcontentview()方法
  • 4、在往下就是一个树形结构的视图结构,viewgroup中嵌套viewgroup和view
framelayout rootview = findviewbyid(android.r.id.content); 
relativelayout relativelayout = (linearlayout) rootview.getchildat(0);//获取activity的根部局

注意:无论是measure过程还是layout过程还是draw过程,永远都是从view树的根节点往下树形递归的开始测量或者计算。

5、view的坐标系

注意:

1、当view没有发生动画偏移的时候,getx()和getleft()相等,如果由translation的时候,getx() = getleft() + gettranslationx()

2、getleft()等获取的值是相对父容器而言的

6、view树的绘制流程

view树的绘制是交给viewrootimpl去负责的,入口在 viewrootimpl.setview() –> requestlayout()方法中进行的,最终调用到了一个叫做performtraversals()方法里面,这里面就开始了真正的绘制流程工作,平时写的ondraw、onmeasure、onlayout也都在这里边。

6.1 measure过程

1、系统为什么需要measure过程

因为我们在写布局的时候要针对不同的机型做适配,不能写死view的高度和宽度,经常使用wrap_content这种形式,为了适配这种自适应布局的机制,所以系统需要进行measure测量

2、measure过程做了什么事情

确定每个view在屏幕上显示的时候所需要的真实的宽度和高度

3、viewgroup如何向子view传递限制信息

通过measurespec,从名字上来看叫做测量规格,它封装了父容器对子view的布局上的限制,内部提供了宽高的信息(specmode、specsize),specsize是指在某种情况下specmode下的参考尺寸。

6.2 分析自定义viewgroup的onmeasure过程

@override
protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  int width = 0;//最终确定的宽度
  int height = 0;//最终确定的高度
  //1、首先测量自身
  super.onmeasure(widthmeasurespec, heightmeasurespec);
  //2、为每个子view计算测量的限制信息mode/size
  int widthmeasurespecmode = measurespec.getmode(widthmeasurespec);
  int widthmeasurespecsize = measurespec.getsize(widthmeasurespec);
  int heightmeasurespecmode = measurespec.getmode(heightmeasurespec);
  int heightmeasurespecsize = measurespec.getsize(heightmeasurespec);
  //3、测量子view;把上一步确定的限制信息,传递给每一个子view,然后子view开始measure自己的尺寸
  int childcount = getchildcount();
  for(int i=0;i<childcount;i++){
    view child = getchildat(i);
    measurechild(child,widthmeasurespec,heightmeasurespec);//这个方法就是确定子view的测量大小
  }
  //4、根据子view的测量尺寸以及自身的specmode计算自己的尺寸
  switch (widthmeasurespecmode) {
    case measurespec.exactly://如果是确定值,则使用确定值
      width = widthmeasurespecsize;
    case measurespec.at_most://如果是根据内容定的大小
    case measurespec.unspecified://一般可以不用单独处理
      for(int i=0;i<childcount;i++){
        view child = getchildat(i);
        int childwidth = child.getmeasuredwidth();//这一步只有当measurechild方法执行完之后才能拿到
        width = math.max(childwidth,width);
      }
    default:break;
  }
  switch (heightmeasurespecmode) {
    case measurespec.exactly://如果是确定值,则使用确定值
      height = heightmeasurespecsize;
    case measurespec.at_most://如果是根据内容定的大小
    case measurespec.unspecified:
      for(int i=0;i<childcount;i++){
        view child = getchildat(i);
        int childheight = child.getmeasuredheight();//这一步只有当measurechild方法执行完之后才能拿到
        height+=childheight;
      }
    default:break;
  }
  //保存自身测量后的宽和高
  setmeasureddimension(width,height);
}

要明确一点,重写自定义viewgroup的onmeasure方法是为了确定这个view的真正的宽度和高度,很明显这与它的子view脱离不了干系。

onmeasure()方法中的两个参数,是这个自定义viewgroup的父view给出的参考值,具体怎么给出的呢,可以参考viewgroup的measurechild()方法,这个方法我们在重写onmeasure时也用到了,看这个方法的第一个参数好像是view,看起来好像跟我们自定义viewgroup没啥关系,但别忘了,viewgroup也是一个view,所以,我们的自定义viewgroup的onmeasure()方法中的两个参数就是由下面的方法产生的,具体来讲就是下面的 childwidthmeasurespec和childheightmeasurespec。

总结一句话就是:子view(包括子viewgroup)的widthmeasurespec和heightmeasurespec的确定是由子view本身的layoutparams以及父view(包括父viewgroup)的widthmeasurespec和heightmeasurespec确定的。这一段逻辑是viewgroup#getchildmeasurespec()。有个表格

protected void measurechild(view child, int parentwidthmeasurespec,
        int parentheightmeasurespec) {
    final layoutparams lp = child.getlayoutparams();

    final int childwidthmeasurespec = getchildmeasurespec(parentwidthmeasurespec,
            mpaddingleft + mpaddingright, lp.width);
    final int childheightmeasurespec = getchildmeasurespec(parentheightmeasurespec,
            mpaddingtop + mpaddingbottom, lp.height);

    child.measure(childwidthmeasurespec, childheightmeasurespec);
}

知道了自身的measurespec参数,下面就好办了,那么直接调用view.measure(childwidthmeasurespec, childheightmeasurespec)完成自身的测量。

关键来了, 在view的measure方法里面会调用onmeasure方法,如果当前view是一个普通的view,则直接执行这里的方法,完成普通view的测量过程,但是, 如果当前view是一个viewgroup就会调用自身重写好的onmeasure方法,也就是我们重写的方法。

对于自定义viewgroup重写的onmeasure方法需要结合子view的宽度和高度,以及自身的layoutparams的模式来确定最终的宽度和高度

那么对于普通view是否就不需要重写onmeasure了呢,源码不是已经写好了吗?

看一下代码:

protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    setmeasureddimension(getdefaultsize(getsuggestedminimumwidth(), widthmeasurespec),
            getdefaultsize(getsuggestedminimumheight(), heightmeasurespec));
}
public static int getdefaultsize(int size, int measurespec) {
    int result = size;
    int specmode = measurespec.getmode(measurespec);
    int specsize = measurespec.getsize(measurespec);
    switch (specmode) {
    case measurespec.unspecified:
        result = size;
        break;
    case measurespec.at_most:
    case measurespec.exactly:
        result = specsize;
        break;
    }
    return result;
}

发现,无论是精确模式,还是wrap_content模式最后值都是之前由子view本身的layoutparams以及父view(包括父viewgroup)的widthmeasurespec和heightmeasurespec确定的measurespecsize值大小,通过查表可知,如果当普通的自定义view的宽度或者高度被设置成了为了wrap_content的话,它的效果跟mathch_parent效果一样,所以普通的自定义view需要对wrap_content这一情况进行完善,参考textview

6.3 分析自定义viewgroup的onlayout过程

onlayout的中后四个参数,指的是,当前自定义viewgroup在它的父布局中的上下左右坐标,通过这个坐标可以得到当前自定义viewgroup的测量宽度和高度,不过一般也不需要用到这个四个参数,因为可以直接通过 getmeasuredwidth() 方法得到

所以onlayout的核心目的就是计算每一个控件的left、top、right、bottom坐标,然后通过 child.layout()方法set进去就行了,所以onlayout主要工作就在于如何确定这四个参数。

追踪child.layout()方法进去看看:

6.4 自定义layout实战

流布局:

package com.example.materialdesign.selfview;
import android.content.context;
import android.os.build;
import android.util.attributeset;
import android.view.view;
import android.view.viewgroup;
import androidx.annotation.requiresapi;
public class flowlayout extends viewgroup {
  public flowlayout(context context) {
    super(context);
  }
  public flowlayout(context context, attributeset attrs) {
    super(context, attrs);
  }
  public flowlayout(context context, attributeset attrs, int defstyleattr) {
    super(context, attrs, defstyleattr);
  }
  @requiresapi(api = build.version_codes.lollipop)
  public flowlayout(context context, attributeset attrs, int defstyleattr, int defstyleres) {
    super(context, attrs, defstyleattr, defstyleres);
  }
  @override
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
    int linewidth = 0;//记录每一行的宽度,最终的宽度是由所有行中的最大值
    int lineheight = 0;//记录每一行的高度,取决于每一行中最高的那个组件
    int resh = 0;//最终的高度
    int resw = 0;//最终的宽度
    //1、首先测量自身
    super.onmeasure(widthmeasurespec, heightmeasurespec);
    //2、为每个子view计算测量的限制信息mode/size
    int widthmeasurespecmode = measurespec.getmode(widthmeasurespec);
    int widthmeasurespecsize = measurespec.getsize(widthmeasurespec);
    int heightmeasurespecmode = measurespec.getmode(heightmeasurespec);
    int heightmeasurespecsize = measurespec.getsize(heightmeasurespec);
    //3、测量每个子view的宽度和高度
    int childcount = getchildcount();
    for (int i = 0; i < childcount; i++) {
      view child = getchildat(i);
      measurechild(child, widthmeasurespec, heightmeasurespec);
      marginlayoutparams lp = (marginlayoutparams) child.getlayoutparams();
      int childmeasuredwidth = child.getmeasuredwidth() + lp.leftmargin + lp.rightmargin;
      int childmeasuredheight = child.getmeasuredheight() + lp.bottommargin + lp.topmargin;

      if (linewidth + childmeasuredwidth > widthmeasurespecsize) {//当前行的的宽度已经加上当前view的宽度已经大于建议值宽度了
        //需要换行
        resw = math.max(resw, linewidth);
        resh += lineheight;
        //重新赋值
        linewidth = childmeasuredwidth;
        lineheight = childmeasuredheight;
      } else {//不需要换行则累加
        linewidth += childmeasuredwidth;
        lineheight = math.max(lineheight,childmeasuredheight);//取最高的那个
      }
      if (i == childcount - 1) {//别忘了单独处理最后一行的最后一个元素的情况
        resh += lineheight;
        resw = math.max(resw, linewidth);
      }
    }
    setmeasureddimension((widthmeasurespecmode==measurespec.exactly)?widthmeasurespecsize:resw,
    (heightmeasurespecmode==measurespec.exactly)?heightmeasurespecsize:resh);
  }
  @override
  protected void onlayout(boolean changed, int l, int t, int r, int b) {
    int count = getchildcount();
    int linewidth = 0;//累加当前行的行宽
    int lineheight = 0;//累加当前行的行高
    int top = 0, left = 0;//当前控件的left坐标和top坐标
    for (int i = 0; i < count; i++) {
      view child = getchildat(i);
      marginlayoutparams lp = (marginlayoutparams) child.getlayoutparams();
      int childmeasuredwidth = child.getmeasuredwidth() + lp.leftmargin + lp.rightmargin;
      int childmeasuredheight = child.getmeasuredheight() + lp.bottommargin + lp.topmargin;
      //根据是否要换行,来计算当前控件的top坐标和left坐标,是否换行是需要考虑margin的
      if (childmeasuredwidth + linewidth > getmeasuredwidth()) {
        top += lineheight;
        left = 0;
        lineheight = childmeasuredheight;
        linewidth = childmeasuredwidth;
      } else {
        linewidth += childmeasuredwidth;
        lineheight = math.max(lineheight, childmeasuredheight);
      }
      //在已知left和top情况下计算当前view的上下左右坐标,在真正给当前view定位置时候需要考虑margin的
      int lc = left + lp.leftmargin;
      int tc = top + lp.topmargin;
      int rc = lc + child.getmeasuredwidth();//注意在layout的时候没有算上margin
      int bc = tc + child.getmeasuredheight();
      child.layout(lc, tc, rc, bc);
      left += childmeasuredwidth;//下一起点算上margin
    }
  }
  @override
  protected layoutparams generatelayoutparams(layoutparams p) {
    return new marginlayoutparams(p);
  }
  @override
  public layoutparams generatelayoutparams(attributeset attrs) {
    return new marginlayoutparams(getcontext(),attrs);
  }
  @override
  protected layoutparams generatedefaultlayoutparams() {
    return new marginlayoutparams(layoutparams.match_parent,layoutparams.match_parent);
  }
}

注意:上述代码实际上可能不符合业务预期,在于 measurechild(child, widthmeasurespec, heightmeasurespec);这一句,我们直接调用系统的方法去获得子view的measurespec,但实际上获取到的值不一定是我们想要的,即下图的值不一定符合我们的业务,所以在真正测量子view的时候,需要针对子view的match_parent情况或者wrap_content情况进行特殊处理

一般情况下是针对子view是match_parent的情况做处理,比如我们自定义的flowlayout,如果flowlayout是match_parent、子view是match_parent的话,就需要特殊处理了,根据模式表子view所占的空间将充满整个父view的剩余空间,这一点符合代码逻辑但是可能不会符合业务需求 

6.5 细节

1、getmeasuredwidth和getwidth的区别

getmeasuredwidth是在measure的过程结束后就可以获得到的view测量宽度值;而getwidth是在layout过程结束后通过mright-mleft得到的;一般情况下,二者是相等的,但有可能不相等,getwidth取决于layout过程中怎么算的四点坐标值。

2、ondraw、onmeasure以及onlayout会多次调用,所以这里面尽量不要频繁的new 对象

3、调用view.invalidate()以及requestlayout()有什么区别:

这个方法是用来刷新整个视图的,当视图的内容,可见性发生变化,ondraw(canvas canvas)方法会被调用。 调用invalidate()方法不会导致measure和layout方法被调用。

requestlayout()是在view的布局发生变化时调用,布局的变化包含位置,大小。重新触发measure,layout,draw

注意:

  • 1.这个方法不能在正在布局的时候调用
  • 2.调用这个方法,会导致布局重绘,调用measure,layout,draw的过程。

到此这篇关于android自定义view原理(实战)的文章就介绍到这了,更多相关android自定义view内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!