关于onMeasure()和onLayout()略写

来源:互联网 发布:淘宝手机代购哪家好 编辑:程序博客网 时间:2024/06/06 19:29

      当在编写很复杂的UI时,我们通常会创建类去集成ViewGroup:如LinearLlayout,RelativeLayout,FrameLayout等。

继承后通常会重写如下方法

       onMeasure(int widthMeasureSpec, int heightMeasureSpec) 和

       onLayout(boolean changed, int l, int t, int r, int b)这两个方法。onLayout方法在onMeasure方法之后执行。


       贴出一些代码:

/** * 作用:在控件的父元素正要放置它的子控件时调用 *  * @param widthMeasureSpec,heightMeasureSpec 它们指明控件可获得的空间 以 及关于这个空间描述的元数据 *  * UNSPECIFIED:父布局没有给子布局任何限制,子布局可以任意大小。       EXACTLY:父布局决定子布局的确切大小。不论子布局多大,它都必须限制在这个界限里。                (当父布局定义为一个固定像素或者fill_parent时就是EXACTLY模式)       AT_MOST:子布局可以根据自己的大小选择任意大小。(当布局定义为wrap_content时就是AT_MOST模式)              MeasureSpec:包含一个尺寸和模式       */@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);final int width = MeasureSpec.getSize(widthMeasureSpec);//获得子控件的宽度final int widthMode = MeasureSpec.getMode(widthMeasureSpec);//模式final int heightMode = MeasureSpec.getMode(heightMeasureSpec);//高度模式if (widthMode!=MeasureSpec.EXACTLY) {throw new IllegalStateException("宽度模式只能为EXACTLY");}if (heightMode!=MeasureSpec.EXACTLY) {throw new IllegalStateException("高度模式只能为EXACTLY");}final int count =getChildCount();for (int i = 0; i < count; i++) {getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);}scrollTo(curScreen*width, 0);}

该段代码是随便拿来的。

/** * 在onMeasure方法之后执行 * 作用:父视图为子视图在屏幕上分配实际的宽度和高度(子视图位置) * @param changed 布局是否发生变化*/@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {        int childleft=0;        for (int i = 0; i < this.getChildCount(); i++) {View childView = this.getChildAt(i);//获得子视图if (childView.getVisibility() != View.GONE) {int viewWdith = childView.getMeasuredWidth();//子视图的宽度childView.layout(childleft, 0, childleft+viewWdith, childView.getMeasuredHeight());//left,top,rigth,bottomchildleft=childleft+viewWdith;}}}


      

0 0