• 自定义View系列教程03--onLayout源码详尽分析



    深入探讨Android异步精髓Handler


    站在源码的肩膀上全解Scroller工作机制


    Android多分辨率适配框架(1)— 核心基础
    Android多分辨率适配框架(2)— 原理剖析
    Android多分辨率适配框架(3)— 使用指南


    自定义View系列教程00–推翻自己和过往,重学自定义View
    自定义View系列教程01–常用工具介绍
    自定义View系列教程02–onMeasure源码详尽分析
    自定义View系列教程03–onLayout源码详尽分析
    自定义View系列教程04–Draw源码分析及其实践
    自定义View系列教程05–示例分析
    自定义View系列教程06–详解View的Touch事件处理
    自定义View系列教程07–详解ViewGroup分发Touch事件
    自定义View系列教程08–滑动冲突的产生及其处理


    PS:如果觉得文章太长,那就直接看视频


    在经过measure阶段以后,系统确定了View的测量大小,接下来就进入到layout的过程。

    在该过程中会确定视图的显示位置,即子View在其父控件中的位置。

    嗯哼,我们直接扒开源码从View的layout( )开始入手。

    //l, t, r, b分别表示子View相对于父View的左、上、右、下的坐标
    public void layout(int l, int t, int r, int b) {
            if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
                onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }
    
            int oldL = mLeft;
            int oldT = mTop;
            int oldB = mBottom;
            int oldR = mRight;
    
            boolean changed = isLayoutModeOptical(mParent) ?
                    setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
    
            if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
                onLayout(changed, l, t, r, b);
                mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
    
                ListenerInfo li = mListenerInfo;
                if (li != null && li.mOnLayoutChangeListeners != null) {
                    ArrayList<OnLayoutChangeListener> listenersCopy =
                            (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                    int numListeners = listenersCopy.size();
                    for (int i = 0; i < numListeners; ++i) {
                        listenersCopy.get(i).onLayoutChange(this,l,t,r,b,oldL,oldT,oldR,oldB);
                    }
                }
            }
    
            mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
            mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
        }

    在该方法中的主要实现
    1 确定该View在其父View中的位置,请参见代码第13-14行。
    在该处调用setFrame()方法,在该方法中把l,t, r, b分别与之前的mLeft,mTop,mRight,mBottom一一作比较,假若其中任意一个值发生了变化,那么就判定该View的位置发生了变化
    2 若View的位置发生了变化则调用onLayout()方法,请参见代码第17行

    嗯哼,我们就顺着这个思路去看看onLayout()的源码

    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    
    }

    额,View的onLayout()方法竟然是一个空方法!这是为啥呢?
    先瞅瞅官方文档对该方法的介绍:

    Called from layout when this view should assign a size and position to each of its children.

    噢,原来文档中说了:在layout方法中调用该onLayout()用于指定子View的大小和位置。
    谁才有子View呢?用你的小脑袋瓜想想。
    哇哈,当然是ViewGroup!
    这也就是说:ViewGroup会调用onLayout()决定子View的显示位置。

    好吧,既然如此就去看ViewGroup中的onLayout()方法是怎么实现的;嗯哼,接着看源码

    protected abstract void onLayout(boolean changed,int l, int t, int r, int b);

    额,ViewGroup的onLayout()竟然是一个抽象方法!这就意味着啥呢?
    这就是说ViewGroup的子类都必须重写这个方法,实现自己的逻辑。比如:FrameLayou,LinearLayout,RelativeLayout等等布局都需要重写这个方法,在该方法内依据各自的布局规则确定子View的位置。

    在此以LinearLayout为例,看看ViewGroup对于onLayout()方法的实现。

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
            if (mOrientation == VERTICAL) {
                layoutVertical(l, t, r, b);
            } else {
                layoutHorizontal(l, t, r, b);
            }
        }

    在LinearLayout的onLayout()方法中分别处理了水平线性布局和垂直线性布局。在此,就选择layoutVertical()继续往下看。

    void layoutVertical(int left, int top, int right, int bottom) {
        final int paddingLeft = mPaddingLeft;
        int childTop;
        int childLeft;
        final int width = right - left;
        int childRight = width - mPaddingRight;
    
        int childSpace = width - paddingLeft - mPaddingRight;
    
        final int count = getVirtualChildCount();
    
        final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
        final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
    
        switch (majorGravity) {
              case Gravity.BOTTOM:
                  childTop = mPaddingTop + bottom - top - mTotalLength;
                   break;
    
              case Gravity.CENTER_VERTICAL:
                  childTop =mPaddingTop+(bottom-top-mTotalLength) / 2;
                  break;
    
              case Gravity.TOP:
              default:
                  childTop = mPaddingTop;
                  break;
        }
    
        for (int i = 0; i < count; i++) {
            final View child = getVirtualChildAt(i);
            if (child == null) {
                childTop += measureNullChild(i);
            } else if (child.getVisibility() != GONE) {
                final int childWidth = child.getMeasuredWidth();
                final int childHeight = child.getMeasuredHeight();
    
                final LinearLayout.LayoutParams lp =
                            (LinearLayout.LayoutParams) child.getLayoutParams();
    
                int gravity = lp.gravity;
                if (gravity < 0) {
                    gravity = minorGravity;
                }
                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = paddingLeft + ((childSpace - childWidth) / 2)
                                    + lp.leftMargin - lp.rightMargin;
                        break;
    
                    case Gravity.RIGHT:
                        childLeft = childRight - childWidth - lp.rightMargin;
                        break;
    
                    case Gravity.LEFT:
                    default:
                        childLeft = paddingLeft + lp.leftMargin;
                        break;
                }
    
                if (hasDividerBeforeChildAt(i)) {
                    childTop += mDividerHeight;
                }
    
                childTop += lp.topMargin;
                setChildFrame(child,childLeft,childTop+ getLocationOffset(child),
                            childWidth, childHeight);
                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
    
                i += getChildrenSkipCount(child, i);
            }
        }
    }

    这里的逻辑不是特别简单,我们看几个重要的步骤。
    第一步:
    计算child可使用空间的大小,请参见代码第8行

    第二步:
    获取子View的个数,请参见代码第10行

    第三步:
    计算childTop从而确定子View的开始布局位置,请参见代码第12-28行

    第四步:
    确定每个子View的位置,请参见代码第30-74行
    这一步是最关键的步骤,我们瞅瞅它的主要操作
    1 得到子View测量后的宽和高,请参见代码第35-36行.
    这里获取到的childWidth和childHeight就是在measure阶段所确立的宽和高
    2 得到子View的LayoutParams,请参见代码第38-39行.
    3 依据子View的LayoutParams确定子View的位置,请参见代码第41-69行.
    我们可以发现在setChildFrame()中又调用了View的layout()方法来确定子View的位置。

    到这我们就可以理清楚思路了:
    ViewGroup首先调用了layout()确定了自己本身在其父View中的位置,然后调用onLayout()确定每个子View的位置,每个子View又会调用View的layout()方法来确定自己在ViewGroup的位置。
    概况地讲:
    View的layout()方法用于View确定自己本身在其父View的位置
    ViewGroup的onLayout()方法用于确定子View的位置

    为了更好的理解,在此用一个简单的示例模拟ViewGroup的onLayout()过程

    首先我们自定义一个ViewGroup

    package com.cc.testlayout;
    import android.content.Context;
    import android.graphics.Canvas;
    import android.util.AttributeSet;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class ViewGroupSubClass extends ViewGroup{
        public ViewGroupSubClass(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int childCount=getChildCount();
            if(childCount>0){
                View child=getChildAt(0);
                measureChild(child,widthMeasureSpec,heightMeasureSpec);
            }
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            int childCount=getChildCount();
            if(childCount>0){
                View child=getChildAt(0);
                int measuredWidth=child.getMeasuredWidth();
                int measuredHeight=child.getMeasuredHeight();
                child.layout(0,0,measuredWidth,measuredHeight);
            }
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
        }
    }
    

    主要步骤如下:
    第一步:
    在onMeasure()中测量子View
    第二步:
    在onLayout()中确定子View的位置

    定义好ViewGroup之后,将其放入布局文件中

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="#A5FD01"
        tools:context="com.cc.testlayout.MainActivity">
    
        <com.cc.testlayout.ViewGroupSubClass
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
    
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/j" />
        </com.cc.testlayout.ViewGroupSubClass>
    
    </RelativeLayout>
    

    代码有了,布局文件也写了,运行一下瞅瞅效果。
    这里写图片描述

    嗯哼,看到了吧,我把一个ImageView放入自定义ViewGroup中展示了我女朋友的照片。


    至此,我们已经看完了measure和layout这两个过程,对于一些问题我们做一个小的总结
    1 获取View的测量大小measuredWidth和measuredHeight的时机。
    在某些复杂或者极端的情况下系统会多次执行measure过程,所以在onMeasure()中去获取View的测量大小得到的是一个不准确的值。为了避免该情况,最好在onMeasure()的下一阶段即onLayout()中去获取。
    2 getMeasuredWidth()和getWidth()的区别
    在绝大多数情况下这两者返回的值都是相同的,但是结果相同并不说明它们是同一个东西。
    首先,它们的获取时机是不同的。
    在measure()过程结束后就可以调用getMeasuredWidth()方法获取到View的测量大小,而getWidth()方法要在layout()过程结束后才能被调用从而获取View的实际大小。
    其次,它们返回值的计算方式不同。
    getMeasuredWidth()方法中的返回值是通过setMeasuredDimension()方法得到的,这点我们之前已经分析过,在此不再赘述;而getWidth()方法中的返回值是通过View的右坐标减去其左坐标(right-left)计算出来的。
    3 刚才说到了关于View的坐标,在这就不得不提一下:
    view.getLeft(),view.getRight(),view.getBottom(),view.getTop();
    这四个方法用于获取子View相对于父View的位置。
    但是请注意:
    getLeft( )表示子View的左边距离父View的左边的距离
    getRight( )表示子View的右边距离父View的左边的距离
    getTop( )表示子View的上边距离父View的上边的距离
    getBottom( )表示子View的下边距离父View的上边的距离
    在此,画一个示例图作为参考
    这里写图片描述
    4 直接继承自ViewGroup可能带来的复杂处理。
    刚通过一个例子简单模拟了ViewGroup的onLayout()过程;其实,说简单已经算是含蓄的了;如果要粗暴地说那就是简单得令人发指。因为项目开发中实际的情况可能远比这个复杂;比如,在ViewGroup中包含了多个View,每个View都设置了padding和margin,除此之外还可能包含各种嵌套。在这种情况下,我们在onMeasure()和onLayout()中都要花费大量的精力来处理这些问题。所以在一般情况下,我们可以选择继承自LinearLayout,RelativeLayout等系统已有的布局从而简化这两部分的处理。


    who is the next one? ——> draw

    PS:如果觉得文章太长,那就直接看视频


  • 相关阅读:
    ios获取iphone手机设备型号
    iOS项目中所有icon的尺寸以及命名
    c++达内视频
    ffmpeg教程
    FFMPEG SDK 教程
    minicom 下载
    线程同步的几种方法的总结
    多线程笔试面试概念问答
    buntu Rhythmbox解决中文乱码
    菜鸟学习ios
  • 原文地址:https://www.cnblogs.com/hehe520/p/6147699.html
Copyright © 2020-2023  润新知