Android 自定义View学习(一)——准备

学习资料:

感谢以上各位大神前辈们 :)

除了爱哥的自定义系列博客,再推荐一个非常不错的系列,GcsSloop的自定义系列,可以看完我写的再去看,我写的很基础,适合刚开始学习自定义View的同学来了解基础知识,原理及更深入的知识,可看两位大神的系列 : )


安利,安利,安利

扔物线大神的 HenCoder 自定义VIew系列


整个系列学习,记录的大概过程:

本篇就是个读书笔记而已


1.Android控件架构

Android中的每个控件都会在界面中占据一个矩形区域。控件大致分为ViewViewGroupViewGroup控件作为父类控件可以包含多个View控件。

View树状图

通过ViewGroup,整个界面控件形成树形结构,也即是控件树。上层控件负责下层控件的测量和绘制,并传递交互事件。在一个Activity中,findViewById()就是在控件树中以树的深度优先遍历来查找对应的元素。

在每棵树的顶部,都有一个ViewParent对象,所有的交互管理事件都有这个ViewParent对象调度和分配


通常情况下,在Activity中使用setContent()方法设置一个布局在调用本方法后,布局内容才会真正显示出来。

UI界面架构图

每个Activity都包含有一个Window对象,通常是PhoneWindowPhoneWindow将一个DecorView设置为整个应用的窗口的根ViewDecorView作为窗口界面顶层视图,里面封装了一些窗口操作的通用方法。

DecorView将内容显示在PhoneWindow上,并通过WindowManagerService来进行接收,并通过Activity对象来回调对应的onClickListener。显示时,将屏幕分成两个部分,TitleViewContentViewContent是一个idcontentFrameLayoutactivity_main.xml就在其中。


通过以上就可以得到下面的标准视图树:

标准视图树

视图树的第二层加载一个LinearLayout作为ViewGroup。这一层布局结构会根据对应的参数设置不同的布局。

最常用的布局,上面显示TitleBar下面是Content。如果用户通过设置requestWindowFeature(Window.FEATURE_NO_TITLE)来设置全屏显示,视图树就只有Content。这也是为什么requestWindowFeature()要在setContent()之前生效的原因。

当程序在onCreate()方法中调用了setContentView()方法后,ActivityManagerService会回调onResume()方法,系统会把整个DecorView添加进PhoneWindow中,显示出来后,完成界面的绘制。


2.坐标体系

View的位置只要由它的四个顶点来决定。分别对应于View的四个属性:

  • topgetTop()左上角的纵坐标
  • leftgetLeft() 左上角的横坐标
  • rightgetRight() 右下角的横坐标
  • bottomgetBottom() 右下角的纵坐标

View的这些坐标都是相对于View的父容器来说。

坐标系

在Android 3.0 后,View增加了:xytranlastionXtranslationYxyView左上角的坐标,tranlastionXtranslationYView左上角相对于父容器的偏移量。
换算关系:
x = left + translationX
y = top + translationY
需要注意的是,View在平移过程中,top和left表示的原始左上角的位置信息,其值并不会发生改变,此时发生改变的是xytranlastionXtranslationY

图颜色配的有点多。 :)


3.View的测量

一个View显示在屏幕上需要经历三个流程:测量,布局,绘制

测量的目的在于告诉系统绘制一个多大的,位置在哪里。这个过程在onMeasure()方法中进行。

测量主要依赖MeasureSppec类。MeasureSpec是一个32位的int值,高2位为测量的模式,低30位为测量的大小。

测量的模式共有三种:

  • EXACTLY 精确模式,两种情况
    控件的layout_width,layout_height
  1. 指定数值时,例如layout_width="100dp"
  2. 指定为match_parent
  • AT_MOST 最大值模式
    控件的layout_width,layout_height指定为wrap_content

控件大小一般会随着子空间的或内容的变化而变化,此时要求控件的尺寸只要不超过父类控件允许的最大尺寸即可

  • UNSPECIFIED 未指明模式
    不指定控件大小,View想多大就多大。

View类默认的onMeasure()方法只支持EXACTLY模式。自定义View时,需要重写onMeasure()方法后,才可以支持其他的模式。假如想要自定义的控件支持wrap_content,就要在onMeasure()中告诉系统自定义控件wrap_content时的大小。


3.1 最基础的实现

用来测试onMeasure()方法。

public class MeasureView extends View {
    public MeasureView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

在布局中使用:

 <com.szlk.customview.custom.MeasureView
     android:id="@+id/mv_custom_activity"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="@color/colorAccent" />
wrap_content效果

运行之后,wrap_content在此时和match_parent效果是一样的。都是沾满全屏。此时在Acitivity中拿到的MeasureView的大小和match_parent是一样的。


3.2 修改onMeasure()方法

重写onMeasure()方法后

重写onMeasure方法

public class MeasureView extends View {
    public MeasureView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),measuredHeight(heightMeasureSpec));
    }

    /**
     * 测量宽
     * @param widthMeasureSpec
     */
    private int measureWidth(int widthMeasureSpec) {
        int result ;
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY){
            result = specSize;
        }else {
            result = 200;
            if (specMode == MeasureSpec.AT_MOST){
                    result = Math.min(result,specSize);
            }
        }
        return result;
    }

    /**
     * 测量高
     * @param heightMeasureSpec
     */
    private int measuredHeight(int heightMeasureSpec) {
        int result ;
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY){
            result = specSize;
        }else{
            result = 200;
            if(specMode == MeasureSpec.AT_MOST){
                result = Math.min(result,specSize);
            }
        }
        return  result;
    }
}

加入了利用MeasureSpec来判断模式。根据不同模式,进行对宽高赋值。在AT_MOST也就是wrap_content时,默认最大的宽高都是200px


3.3 涉及的部分源码

  • getMode()
 /**
  * Extracts the mode from the supplied measure specification.
  *
  * @param measureSpec the measure specification to extract the mode from
  * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
  *         {@link android.view.View.MeasureSpec#AT_MOST} or
  *         {@link android.view.View.MeasureSpec#EXACTLY}
  */
 @MeasureSpecMode
 public static int getMode(int measureSpec) {
    //noinspection ResourceType
    return (measureSpec & MODE_MASK);
}

@return可知,返回结果就是MeasureSpec的三种模式


  • getSize()
 /**
  * Extracts the size from the supplied measure specification.
  *
  * @param measureSpec the measure specification to extract the size from
  * @return the size in pixels defined in the supplied measure specification
  */
  public static int getSize(int measureSpec) {
     return (measureSpec & ~MODE_MASK);
  }

返回的是在布局文件中声明的值,结果是px


  • onMeasure()
    /**
     * <p>
     * Measure the view and its content to determine the measured width and the
     * measured height. This method is invoked by {@link #measure(int, int)} and
     * should be overridden by subclasses to provide accurate and efficient
     * measurement of their contents.
     * </p>
     *
     * <p>
     * <strong>CONTRACT:</strong> When overriding this method, you
     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
     * measured width and height of this view. Failure to do so will trigger an
     * <code>IllegalStateException</code>, thrown by
     * {@link #measure(int, int)}. Calling the superclass'
     * {@link #onMeasure(int, int)} is a valid use.
     * </p>
     *
     * <p>
     * The base class implementation of measure defaults to the background size,
     * unless a larger size is allowed by the MeasureSpec. Subclasses should
     * override {@link #onMeasure(int, int)} to provide better measurements of
     * their content.
     * </p>
     *
     * <p>
     * If this method is overridden, it is the subclass's responsibility to make
     * sure the measured height and width are at least the view's minimum height
     * and width ({@link #getSuggestedMinimumHeight()} and
     * {@link #getSuggestedMinimumWidth()}).
     * </p>
     *
     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
     *                         The requirements are encoded with
     *                         {@link android.view.View.MeasureSpec}.
     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
     *                         The requirements are encoded with
     *                         {@link android.view.View.MeasureSpec}.
     *
     * @see #getMeasuredWidth()
     * @see #getMeasuredHeight()
     * @see #setMeasuredDimension(int, int)
     * @see #getSuggestedMinimumHeight()
     * @see #getSuggestedMinimumWidth()
     * @see android.view.View.MeasureSpec#getMode(int)
     * @see android.view.View.MeasureSpec#getSize(int)
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

ViewonMeasure()方法源码中,调用了setMeasuredDimension()方法来确定View的宽和高

View的源码23000行。 : )


4.最后

写的都比较表面,目前深入不了,基本就是看Android 群英传第三章的读写笔记。也不晓得能不能对学习自定义View有些帮助。后面学习,遇到一些知识点也会再补充。

下一篇学习了解一下CanvasPaint都是干嘛的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容