Android开发 - LayoutParams类与layout_开头的属性参数关系解析

  • LayoutParams翻译过来就是布局参数子View通过LayoutParams告诉父容器(ViewGroup)应该如何放置自己。从这个定义中也可以看出来LayoutParamsViewGroup是息息相关的,因此脱离ViewGroupLayoutParams是没有意义的。事实上,每个ViewGroup的子类都有自己对应的LayoutParams类,典型的如LinearLayout.LayoutParamsFrameLayout.LayoutParams等,可以看出来LayoutParams都是对应ViewGroup子类的内部类。最基础的LayoutParams是定义在ViewGroup中的静态内部类,封装着View宽度和高度信息,对应着自定义View.xml视图中的layout_widthlayout_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,而是属于这些ViewLayoutParams,这样的命名方式也就显得很贴切了

posted @ 2024-07-23 10:08  阿俊学JAVA  阅读(3)  评论(0编辑  收藏  举报