Android UI:ViewTree中的事件传递

文章目录

    • ViewTree: 组合模式
    • measure事件的传递
      • 事件传递: View/ViewGroup的measure和onMeasure
      • LinearLayout重写onMeasure
      • RelativeLayout重写onMeasure
    • layout事件的传递
      •  事件传递:View/ViewGroup的layout和onLayout
      •  LinearLayout重写onLayout
      •  RelativeLayout重写onLayout
    • draw事件的传递
      •  View/ViewGroup的dispatchDraw和onDraw
    • TouchEvent事件的传递
      •  dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent方法
    • 小结

ViewTree:组合模式

View {
    ViewParent mParent;
}
ViewGroup extends View implements ViewParent{
    View[] mChildren;
}

   树状结构传递各种事件

        measure事件

        layout事件

        draw事件

        TouchEvent事件

  

measure事件的传递

        View的measure和onMeasure

class View {
    void measure(int widthMeasureSpec, int heightMeasureSpec) {
        onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            //设置控件的宽高
            setMeasuredDimension(
                getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }
    
}

class ViewGroup {
    //没有重写measure()和onMeasure()方法
}

        View.MeasureSpec

                封装size和mode

                mode包含 UNSPECIFIED、EXACTLY、AT_MOST、

                        UNSPECIFIED

                                父控件不会对子控件进行限制

                        EXACTLY

                                父控件对子控件进行精确尺寸设置:忽视子控件本身的设置

                        AT_MOST

                                父控件对子控件给出上限尺寸        

                API

                        MeasureSpec.getMode(measureSpec)

                        MeasureSpec.getSize(measureSpec)

                        MeasureSpec.makeMeasureSpec(size, mode)

        布局控件重写onMeasure方法

                重写onMeasure方法完成2个任务

                       1.向子控件传递measure事件

                       2.设置布局控件本身的宽高

                                View.setMeasuredDimension(width, height)方法用于设置控件的宽高

                LinearLayout重写onMeasure方法

                     根据属性orientation,选择measureVertical或measureHorizontal

                     步骤

                                1.第一次遍历,记录totalWeight和totalLength

                                        totalLength是累计子控件的宽或高

                              

你可能感兴趣的:(android,ui)