手把手教你写一个自定义 ViewGroup

手把手教你写一个自定义 ViewGroup

关键字:kotlin、custom、ViewGroup

custom view group 书写流程
1. override onLayout

首先,最直觉的做法,就是写下 public class CustomViewGroup extends ViewGroup {} 。对于 kotlin 呢,就是 class CustomViewGroup : ViewGroup {} 。然后,根据编译器的提示,我们去实现 onLayout 方法。那么这个 onLayout 的作用是什么呢?

简单翻阅源码,发现在 View 的源码下找到了答案:

public void layout(int l, int t, int r, int b) {
    // ...
    if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
        // ...    
        onLayout(changed, l, t, r, b);
        // ...     
    }
    // ...

这段代码告诉我们,onLayout 是在 layout 方法中调用的。从命名而角度来看,on 表示在什么什么时候。类似的,我们写自定义 view 的时候经常写的 onMeasure 也是在 measure 方法中调用的。那么聪明的读者,请你告诉我,我们写 activity 的时候写的 onCreate 方法,是不是也是在 Activity 的 create 中调用的呢?

哈哈,当然不是了(请放下你们手中的西瓜刀)。onCreate 是在 Activity 中的 performCreate 方法中调用的。不过,原理是类似的,onXxx 都是在实际做 xxx 的时候被调用。而这些个 xxx 方法基本都是 final 的。

书归正传。这个 onLayout 的用途是什么呢?onLayout 函数是在 layout 函数中调用的,自然就是负责处理布局相关的逻辑。看一下函数签名:

override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int)

四个参数 left、top、right、bottom 相当于给我们画了一个边界,我们就在这个画布上作画,不能超出。之后我们在 onLayout 中的逻辑就是,如何排布我们的 CustomViewGroup 的 children 了。这个需要根据业务来。如果仅仅为了测试的话,我们可以简单的让他们一个接一个排列不留空。
在我们写完了 onLayout 之后,运行项目。不出意外的话,我们是看不到任何东西的。为什么?因为我们还少了非常关键的一个环节:测量。

2. override onMeasure

编译器只告诉了我们,需要 override onLayout,但是没有告诉我们需要 overrid onMeasure。仔细想想,在显示生活中,如果我们想有一个 2d 的纸张来画子 view 的话,那么,我们只知道我的子 view 的排列方式还不够,必须要先告诉别人,我们的纸张的大小,这样我们才能作画。onMeasure 就做了向 CustomViewGroup 的 parent 描述我们需要的大小的工作。

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

    val width = getSize(defaultSize = 300, measureSpec = widthMeasureSpec)
    val height = getSize(defaultSize = 300, measureSpec = heightMeasureSpec)

    measureChildren(widthMeasureSpec, heightMeasureSpec)

    setMeasuredDimension(width, height)
}

其中,measureChildren(widthMeasureSpec, heightMeasureSpec) 完成了递归地 measure 子 view 的工作。最后一句 setMeasuredDimension(width, height) 非常重要,每一个 onMeasure 方法都要去显式地调用它。

3. 上代码
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {

    val width = getSize(defaultSize = 300, measureSpec = widthMeasureSpec)
    val height = getSize(defaultSize = 300, measureSpec = heightMeasureSpec)

    measureChildren(widthMeasureSpec, heightMeasureSpec)

    setMeasuredDimension(width, height)
}

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
    var currentTop = 0
    var currentLeft = 0
    var currentRowHeight = 0
    for (i in 0..childCount) {
        val child = getChildAt(i) ?: continue
        val childWidth = child.measuredWidth
        val childHeight = child.measuredHeight

        // child 的 width or height 超过了 parent 的 width 和 height,直接丢弃
        if (childWidth > measuredWidth
                || childHeight > measuredHeight) {
            continue
        }

        if (currentTop + childHeight > measuredHeight) {
            continue
        }

        if (currentLeft + childWidth > measuredWidth) {
            currentLeft = 0
            currentTop += currentRowHeight
            currentRowHeight = 0
        }

        if (currentLeft + childWidth <= measuredWidth
                && currentTop + childHeight <= measuredHeight) {

            child.layout(currentLeft, currentTop, currentLeft + childWidth, currentTop + childHeight)

            currentLeft += childWidth
            if (childHeight > currentRowHeight) {
                currentRowHeight = childHeight
            }
        }

    }
}


private fun getSize(defaultSize: Int, measureSpec: Int): Int {

    val size = MeasureSpec.getSize(measureSpec)
    val mode = MeasureSpec.getMode(measureSpec)

    when (mode) {
        MeasureSpec.EXACTLY -> {
            return size
        }

        MeasureSpec.AT_MOST -> {
            return Math.min(size, defaultSize)
        }

        MeasureSpec.UNSPECIFIED -> {
            return defaultSize
        }

        else -> {
            return defaultSize
        }
    }
}

代码中,layout child 的关键的句子就是:

child.layout(currentLeft, currentTop, currentLeft + childWidth, currentTop + childHeight)
4. 小结

我们写 CustomViewGroup 的时候,需要一次做这几个事情:

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

推荐阅读更多精彩内容