ViewGroup的LayoutParams理解[通俗易懂]

ViewGroup的LayoutParams理解[通俗易懂]LayoutParams是ViewGroup的一个内部类,声明方式如下publicstaticclassLayoutParams{publicstaticfinalintMATCH_PARENT=-1;publicstaticfinalintWRAP_CONTENT=-2;publicintwidth;publicintheight;

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

LayoutParams是ViewGroup的一个内部类,声明方式如下

public static class LayoutParams { 
   
        public static final int MATCH_PARENT = -1;
        public static final int WRAP_CONTENT = -2;
        public int width;
        public int height;
        
        public LayoutParams(Context c, AttributeSet attrs) { 
   
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
            setBaseAttributes(a,R.styleable.ViewGroup_Layout_layout_width, R.styleable.ViewGroup_Layout_layout_height);
            a.recycle();
        }

        public LayoutParams(int width, int height) { 
   
            this.width = width;
            this.height = height;
        }
        
        public LayoutParams(LayoutParams source) { 
   
            this.width = source.width;
            this.height = source.height;
        }

 }

可以分析到,系统默认为ViewGroup自定义了宽高属性width和height,将其获取方式封装在LayoutParams中,系统考虑所有的View肯定都有宽高,所以就直接统一定义了,有一个疑问为啥不定义在View中,因为子View定义的宽高都是layout_width,layout_height,都是相对于父容器的
接下来分析,系统是如何将这个统一的ViewGroup.LayoutParams宽高属性给到View的呢?

阅读源码布局中View的加载流程,主要分析LayoutInflater#inflate这一步

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) { 
   
       
            final View temp = createViewFromTag(root, name, inflaterContext, attrs);

            ViewGroup.LayoutParams params = null;

            if (root != null) { 
   
                params = root.generateLayoutParams(attrs);
                if (!attachToRoot) { 
   
                    temp.setLayoutParams(params);
                 }
            }                    
}

分析关键代码,是root(ViewGroup)调用了generateLayoutParams(AttributeSet attrs);解析attrs中的layout_width和layout_height属性,将其值封装到了LayoutParams中,之后调用子View的setLayoutParams方法设置到子View中,之后子View就可以获取到width和height了

所以默认情况下父容器的generateLayoutParams只是解析layout_width和layout_height。如果子view需要支持margin属性,不重写父容器的generateLayoutParams的话,之后是子View是获取不到margin属性的

再分析下ViewGroup#generateDefaultLayoutParams,在上面我们分析了ViewGroup#generateLayoutParams它是作用在xml布局解析阶段为子View设置LayoutParams,那么ViewGroup#generateDefaultLayoutParams则是在代码中ViewGroup#addView中调用,我们看下源码

public void addView(View child, int index) { 
   
        if (child == null) { 
   
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }
        LayoutParams params = child.getLayoutParams();
        if (params == null) { 
   
            params = generateDefaultLayoutParams();
            if (params == null) { 
   
                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
            }
        }
        addView(child, index, params);
}

分析源码得知,generateDefaultLayoutParams的调用确实在动态addView中,同样的它也是默认创建的ViewGroup.LayoutParams,只支持width和height的

再分析下ViewGroup#generateLayoutParams(LayoutParams p),分析ViewGroup#addViewInner源码

private void addViewInner(View child, int index, LayoutParams params,boolean preventRequestLayout) { 
   
        if (!checkLayoutParams(params)) { 
   
            params = generateLayoutParams(params);
        }
}

分析可以知道,在addViewInner中会对params进行校验,如果不合法则调用generateLayoutParams(params)帮我们生成一个合法的LayoutParams.我们看下校验规则

protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 
   
        return  p != null;
}

ViewGroup默认的校验规则仅仅是不为空,相关宽松,LinearLayout等一般都会重写,有兴趣可以看源码

再分析下ViewGroup默认的generateLayoutParams(ViewGroup.LayoutParams p)实现

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

仅仅是返回了这个不合法的params,这并不是我们期望的,所以这个用法一般是我们重写checkLayoutParams实现合法的校验规则,然后在重写generateLayoutParams创建合法的LayoutParams,看下LinearLayout的实现

@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 
   
        return p instanceof LinearLayout.LayoutParams;
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { 
   
        if (sPreserveMarginParamsInLayoutParamConversion) { 
   
            if (lp instanceof LayoutParams) { 
   
                return new LayoutParams((LayoutParams) lp);
            } else if (lp instanceof MarginLayoutParams) { 
   
                return new LayoutParams((MarginLayoutParams) lp);
            }
        }
        return new LayoutParams(lp);
}

前面分析了ViewGroup默认的LayoutParams只是支持layout_width和layout_height属性的,因为它内部只有获取这两个属性的逻辑,但是我们实际很多子View都是需要支持margin属性的,怎么办呢?

ViewGroup还为我们定义了一个MarginLayoutParams,是不是相当的便利

public static class MarginLayoutParams extends ViewGroup.LayoutParams { 
   
        public int leftMargin;
        public int topMargin;
        public int rightMargin;
        public int bottomMargin;
        public MarginLayoutParams(Context c, AttributeSet attrs) { 
   
            super();
            ...//省略若干获取margin属性操作代码
        }

}

所以如果我们需要子View支持margin属性,那么我们就可以重写ViewGroup#generateLayoutParams(AttributeSet attrs)和ViewGroup#generateDefaultLayoutParams()返回MarginLayoutParams

问题来了,我如果还想让子View支持更多的属性呢?那么我们可以自定义LayoutParams继承自MarginLayoutParams,在构造方法中书写获取我们自定义属性的逻辑,同样重写上面两个方法,返回我们自定义的LayoutParams,这样子View就可以获取到了

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/193328.html原文链接:https://javaforall.net

(0)
上一篇 2025年11月27日 下午5:22
下一篇 2025年11月27日 下午6:01


相关推荐

  • 网站重构

    网站重构前不久听到这样一个面试的故事 面试官 你准备在我们公司做些什么事情 大致这个意思 面试人 我准备在公司做网站重构 把原来是 table 的页面全部重构成 css div 的 面试官 不好意思 我们的网站都是 css div 的 不需要重构了 面试人 无语了 自从 2004 年阿捷翻译了 网站重构 这本书 网站重构这个词就慢慢的必成了 css div 甚至等同起来 一些朋友

    2026年3月16日
    1
  • c++中STL库 简介 及 使用说明

    c++中STL库 简介 及 使用说明作为 C 标准不可缺少的一部分 STL 应该是渗透在 C 程序的角角落落里的 STL 不是实验室里的宠儿 也不是程序员桌上的摆设 她的激动人心并非昙花一现 本教程旨在传播和普及 STL 的基础知识 若能借此机会为 STL 的推广做些力所能及的事情 到也是件让人愉快的事情 nbsp nbsp nbsp 初识 STL 解答一些疑问 nbsp nbsp nbsp 1 1 一个最关心的问题 什么是 STL nbsp nbsp nbsp 什么是 STL 假如你对 STL 还

    2026年3月18日
    1
  • Python 字符串与数字之间的转换

    Python 字符串与数字之间的转换目录什么是类型转换 为什么做类型转换字符串与数字之间转换的要求字符串与数字之间的转换函数什么是类型转换为何做类型转换将自身数据类型变成新的数据类型 并拥有新的数据类型的所有功能的过程即为类型转换 a 1 无法做数字操作为方便更好的帮助处理业务 将类型变更为更适合业务场景的类型字符串与数字之间转换的要求 str gt number 数字组成的字符串 In 61 int str In 62 float str 3 14159

    2026年3月16日
    2
  • Spring Bean生命周期详解「建议收藏」

    Spring Bean生命周期详解「建议收藏」SpringBean生命周期详解

    2026年1月24日
    4
  • 测试 windows live writer

    测试 windows live writer

    2021年5月8日
    120
  • webservice框架有哪些_webservice框架发布方式

    webservice框架有哪些_webservice框架发布方式毕业了,一直更新技术博客,也跳槽到一家上市的公司,他们产品的主要通讯是通过Webservice,以前对Webservice只是做了大致的了解,今天就在网上找一些开源的知识点,现在市面上主流的夸平台传送有JSON和SOAP两种数据格式,总结一下。以下转自至 http://yulimin.iteye.com/blog/128498新一代的WebServices框架如Axis2、CXF都

    2026年2月9日
    8

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号