自定义ViewGroup都要做些啥

一个是斜体

两个是加粗

三个是斜体加粗

以前都是继承一个线性布局,相对布局,帧布局做点简单修改,从来没有继承过viewGroup来写一个,今天顺道写个测试下,结果发现各种坑啊,我以为就实现onLayout这个抽象方法就完事了,结果。。。

下边代码就是简单实现了下线性布局类似的顺序显示,其他pading,margin都不考虑。就先看下功能

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        System.err.println(tag+"========onLayout======"+changed+"============="+l+"="+r+"=="+t+"==="+b);
        int top=0;
        for(int i=0;i<getChildCount();i++) {
            View child=getChildAt(i);
            if(child!=null) {
                child.layout(l, top, r,top+child.getMeasuredHeight());
                top+=child.getMeasuredHeight();
            }
        }
    }

代码如上,结果测试发现里边的child都看不见,打印日志可以发现child.getMeasuredHeight()这个返回的一直是0,自然看不见了。完事我就把child.getMeasuredHeight()改成一个固定的比如200的值,发现是可以看到的,那原因就是child没有进行测量。

那就去看下FrameLayout咋弄的。代码比较多,咱就抽出关键的代码即可,也就是调用了measureChildWithMargins这个方法

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        System.err.println(tag+"===========onMeasure===========h="+getMeasuredHeight()+"===w="+getMeasuredWidth());
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        for(int i=0;i<getChildCount();i++) {
            View child=getChildAt(i);
            if(child!=null) {
                 measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                //android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
            }
        }
    }

这下以为好了,运行下直接挂了。异常
android.view.ViewGroup.LayoutParams cannot be cast to android.view.ViewGroup.MarginLayoutParams

原因就是如下的代码,可以看到parama进行了强转

    protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

继续看ViewGroup里有如下的几个方法,里边的LayoutParams就是ViewGroup里的一个静态类public static class LayoutParams

    /**
     * Returns a new set of layout parameters based on the supplied attributes set.
     *
     * @param attrs the attributes to build the layout parameters from
     *
     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
     *         of its descendants
     */
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

    /**
     * Returns a safe set of layout parameters based on the supplied layout params.
     * When a ViewGroup is passed a View whose layout params do not pass the test of
     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
     * is invoked. This method should return a new set of layout params suitable for
     * this ViewGroup, possibly by copying the appropriate attributes from the
     * specified set of layout params.
     *
     * @param p The layout parameters to convert into a suitable set of layout parameters
     *          for this ViewGroup.
     *
     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
     *         of its descendants
     */
    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return p;
    }

    /**
     * Returns a set of default layout parameters. These parameters are requested
     * when the View passed to {@link #addView(View)} has no layout parameters
     * already set. If null is returned, an exception is thrown from addView.
     *
     * @return a set of default layout parameters or null
     */
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

那咋办了,修改下这几个方法呗,让默认的child的params就是我们需要的MarginLayoutParams即可

    @Override
    protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
        // TODO Auto-generated method stub
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }
    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams;
    }

    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p);
    }

    @Override
    public CharSequence getAccessibilityClassName() {
        return TouchEventViewGroup.class.getName();
    }
    
    public static class LayoutParams extends MarginLayoutParams {
    //省略掉构造方法了
}

最后说明下如下的关系,marginLayoutParams就是多了写margin参数而已
public static class MarginLayoutParams extends ViewGroup.LayoutParams

继续研究,难道一定要用marginLayoutParams,当然不一定了,如果你的child不需要设置margin那就不用了。
如下修改,剔除掉margin相关的,自然也就不要MarginLayoutParams
其实,核心代码就是child.measure(childWidthMeasureSpec, childHeightMeasureSpec);来测量child的大小

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        System.err.println(tag+"===========onMeasure===========h="+getMeasuredHeight()+"===w="+getMeasuredWidth());
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        for(int i=0;i<getChildCount();i++) {
            View child=getChildAt(i);
            if(child!=null) {
//               measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                //android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
                ViewGroup.LayoutParams lp=child.getLayoutParams();
                final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                        getPaddingLeft() + getPaddingRight(), lp.width);
                final int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                        getPaddingTop()+getPaddingBottom(), lp.height);

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
    }

如果没有特殊的参数,那么直接用MarginLayoutParams即可,如果有自己需要额外添加的参数,那么可以继承这个,自己写一个
看下几个常用的
LinearLayout,多了比重和重心

 public static class LayoutParams extends ViewGroup.MarginLayoutParams

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            TypedArray a =
                    c.obtainStyledAttributes(attrs, com.android.internal.R.styleable.LinearLayout_Layout);

            weight = a.getFloat(com.android.internal.R.styleable.LinearLayout_Layout_layout_weight, 0);
            gravity = a.getInt(com.android.internal.R.styleable.LinearLayout_Layout_layout_gravity, -1);

            a.recycle();
        }

RelativeLayout
多了一对,相对位置的参数,都放在下边的数组里

private int[] mRules = new int[VERB_COUNT];

FrameLayout
多了个child的layout_gravity

public int gravity = UNSPECIFIED_GRAVITY;

总结下其实自定义ViewGroup的核心代码就2行

child.measure(childWidthMeasureSpec, childHeightMeasureSpec); //对childView进行大小测量

child.layout(int l, int t, int r, int b) 对child的位置进行处理,上下左右4个点已经决定了这个child的位置拉。

简单不,嗯,简单,再复杂不会了。

反正知道了基础就这两行,以后看别人写的自定义ViewGroup就好理解了。

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

推荐阅读更多精彩内容