Android开发 - LayoutParams类与layout_开头的属性参数关系解析
-
LayoutParams翻译过来就是布局参数,子View通过LayoutParams告诉父容器(ViewGroup)应该如何放置自己。从这个定义中也可以看出来LayoutParams与ViewGroup是息息相关的,因此脱离ViewGroup谈LayoutParams是没有意义的。事实上,每个ViewGroup的子类都有自己对应的LayoutParams类,典型的如
LinearLayout.LayoutParams
和FrameLayout.LayoutParams
等,可以看出来LayoutParams都是对应ViewGroup子类的内部类。最基础的LayoutParams是定义在ViewGroup中的静态内部类,封装着View的宽度和高度信息,对应着自定义View.xml视图中的layout_width
和layout_height
属性。主要源码如下:public static class LayoutParams { public static final int FILL_PARENT = -1; public static final int MATCH_PARENT = -1; public static final int WRAP_CONTENT = -2; public int width; public int height; ...... /** * XML文件中设置的以layout_开头的属性将在这个方法中解析 */ public LayoutParams(Context c, AttributeSet attrs) { TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); // 解析width和height属性 setBaseAttributes(a, R.styleable.ViewGroup_Layout_layout_width, R.styleable.ViewGroup_Layout_layout_height); a.recycle(); } /** * 使用传入的width和height构建LayoutParams */ public LayoutParams(int width, int height) { this.width = width; this.height = height; } /** * 通过传入的LayoutParams构建新的LayoutParams */ public LayoutParams(LayoutParams source) { this.width = source.width; this.height = source.height; } ...... }
-
弄清楚了LayoutParams的意义,就可以解释为什么在自定义View.xml视图中View的某些属性是以
layout_
开头的了。因为这些属性并不直接属于View,而是属于这些View的LayoutParams,这样的命名方式也就显得很贴切了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)