当前位置:   article > 正文

Android UI: 自定义控件:可换行的布局控件

Android UI: 自定义控件:可换行的布局控件

文章目录

继承ViewGroup

        重写generateLayoutParams,设置子控件的LayoutParams为MarginLayoutParams类型

  1. @Override
  2. public LayoutParams generateLayoutParams(AttributeSet attrs) {
  3. return new MarginLayoutParams(getContext(), attrs);
  4. }

重写onMeasure方法:计算并设置布局控件的高度

子控件的两种情况

        第一种情况:所有子控件的宽度是一致且固定的,布局控件的宽度是固定,高度不确定

                1.获取子控件的固定的宽高

  1. measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, 0);
  2. int childWidth = child.getMeasuredWidth();
  3. int childHeight = child.getMeasuredWidth();

                注意:使用View.getMeasuredWidth/Height()需要确保使用之前,该View对象已经被measure过

                2.获取布局控件的measured宽度

int width = MeasureSpec.getSize(widthMeasureSpec);

                3.计算一行放置多少个子控件,根据子控件个数和布局控件的measured宽度确定布局控件的高度

setMeasuredDimension(width, height);

        第二种情况:每个子控件的宽度都不固定,布局控件的宽度是固定,高度不确定

                1.获取布局控件的measured宽度

int width = MeasureSpec.getSize(widthMeasureSpec);

                2.遍历布局控件中所有子控件

                        1.获取每个子控件的宽度

  1. measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
  2. childWidth = child.getMeasuredWidth();
  3. childHeight = child.getMeasuredHeight();

                       2.累加子控件的宽度,判断是否当前子控件是否需要换行,需要换行,重新累加子控件的宽度,累加高度

            3.遍历结束,设置布局控件的高度

setMeasuredDimension(width, height);

重写onLayout方法:计算并设置每个子控件的位置

遍历布局控件中所有子控件,计算设置每个子控件的位置childLeft, childTop

  1. child.layout(childLeft , childTop,
  2. childLeft+childWidth, childTop+ childHeight);

具体的代码实现

        ​​​​​​​Android UI 代码实现:可换行的布局控件

小结

        

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/236365
推荐阅读
相关标签
  

闽ICP备14008679号