前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android自定义View——布局Layout

Android自定义View——布局Layout

作者头像
艳龙
发布2021-12-16 17:31:21
1.3K0
发布2021-12-16 17:31:21
举报
文章被收录于专栏:yanlongli_艳龙yanlongli_艳龙

之前写了一篇文章介绍自定义View,主要是介绍了自定义View绘制相关的操作。

这里主要是介绍自定义View另一个重要的关键——布局Layout。

绘制相关介绍可以参考:https://cloud.tencent.com/developer/article/2003070

自定义布局

自定义布局主要分为两个部分, 测量(measure()) 和 布局 (layout()

测量过程: 从根view递归调用每一级子view的measure()方法

布局流程:从根view递归调用每一级子view的layout()方法,把测量时得到的子View的尺寸和位置传递给子View。

具体的布局流程如下:

1,在xml中编写View的相关属性 (layout_xxx,设置View的宽高等)

2,父View在自己的onMeasure()方法中,根据xml中设置的要求和自己可用的空间,来计算出对子View的尺寸要求,然后调用子View的measure()方法

3,子View在自己的onMeasure()方法中,根据自己的特性得出自己的期望尺寸(如果是ViewGroup 会重复第二步继续调用子View的measure()方法)

4,父View在子View计算出期望尺寸后,得出子View的实际尺⼨寸和位置保存

5,子View在layout() ⽅方法中将父 View 传进来的⾃自⼰己的实际尺⼨寸和位置保存(如果是 ViewGroup,还会在 onLayout() ⾥里里调⽤用每个字 View 的layout()把它们的尺⼨寸 位置传给它们)

Demo:

下面通过一个demo来展示自定义View的布局,先看效果

标签效果

标签我使用了自定义的View如下,这个属于自定义view的绘制部分,比较简单不是本篇文章介绍的重点,这里就不多说了。

代码语言:javascript
复制
public class TagTextView extends androidx.appcompat.widget.AppCompatTextView {
    private static final int[] COLORS = {
            Color.parseColor("#E91E63"),
            Color.parseColor("#673AB7"),
            Color.parseColor("#3F51B5"),
            Color.parseColor("#2196F3"),
            Color.parseColor("#009688"),
            Color.parseColor("#FF9800"),
            Color.parseColor("#FF5722"),
            Color.parseColor("#795548")
    };
    private static final Random random = new Random();
    private static final int CORNER_RADIUS = (int) Utils.dp2px(4);
    private static final int X_PADDING = (int) Utils.dp2px(20);
    private static final int Y_PADDING = (int) Utils.dp2px(12);


    private static final int X_LAYOUT = (int) Utils.dp2px(4);
    private static final int Y_LAYOUT = (int) Utils.dp2px(4);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    public TagTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    {
        setTextColor(Color.WHITE);
        setTextSize(20);
        paint.setColor(COLORS[random.nextInt(COLORS.length)]);
        setPadding(X_PADDING, Y_PADDING, X_PADDING, Y_PADDING);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRoundRect(X_LAYOUT, Y_LAYOUT, getWidth() - X_LAYOUT, getHeight() - Y_LAYOUT, CORNER_RADIUS, CORNER_RADIUS, paint);
        super.onDraw(canvas);
    }
}

TagLayout 是本篇文章需要介绍的重要内容,先看看具体实现。

代码语言:javascript
复制
class TagLayout : ViewGroup {

    var childLayoutList:ArrayList<Rect> = ArrayList()

    constructor(context: Context, attrs: AttributeSet): super(context, attrs) {

    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var viewWidth = 0
        var viewHeight = 0

        var widthMode = MeasureSpec.getMode(widthMeasureSpec)
        viewWidth = MeasureSpec.getSize(widthMeasureSpec)

        var lineWidthUsed = 0
        var lineMaxHeight = 0

        var heightUsed = 0


        for (index in 0 until childCount) {
            var child = getChildAt(index)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, heightUsed)

            if (widthMode != MeasureSpec.UNSPECIFIED && (lineWidthUsed + child.measuredWidth) > viewWidth) {
                lineWidthUsed = 0
                heightUsed += lineMaxHeight
                lineMaxHeight = 0
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, heightUsed)
            }

            var childBounds: Rect
            if (childLayoutList.size <= index) {
                childBounds = Rect()
                childLayoutList.add(childBounds)
            } else {
                childBounds = childLayoutList[index]
            }


            childBounds.set(lineWidthUsed, heightUsed, lineWidthUsed + child.measuredWidth, heightUsed + child.measuredHeight)

            lineWidthUsed += child.measuredWidth
            lineMaxHeight = Math.max(lineMaxHeight, child.measuredHeight)
        }

        // 加上最后一行 标签的高度
        viewHeight = heightUsed + lineMaxHeight

        viewWidth = View.resolveSizeAndState(viewWidth, widthMeasureSpec, 0)
        viewHeight = View.resolveSize(viewHeight, heightMeasureSpec)

        setMeasuredDimension(viewWidth, viewHeight)
    }

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {

        for (index in 0 until childCount) {
            var view = getChildAt(index)
            var bounds = childLayoutList[index]
            view.layout(bounds.left, bounds.top, bounds.right, bounds.bottom)
        }
    }

    // measureChildWithMargins 需要获取到 margins 需要声明这个
    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }
}

结合布局的流程可以看出:

taglayout 主要实现了 onMeasure()onLayout () 两个函数。

onMeasure(): 计算了子View的大小并保存子View的位置, 同时计算出自己想要的尺寸大小

onLayout (): 比较简单,将之前保存的子View尺寸和大小告诉子view。

tips:

1,View.resolveSizeAndState() 一个修正view 尺寸的方法,自定义view中比较常用

2, setMeasuredDimension(viewWidth, viewHeight) 测量完成后需要调用此方法保存,否则之前测量的就都无效了

END!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/1/4 下午,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 自定义布局
  • Demo:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档