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

文章目录
*

继承ViewGroup

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

复制代码
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

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

子控件的两种情况

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

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

复制代码
measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, 0);
int childWidth = child.getMeasuredWidth();
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.获取每个子控件的宽度

复制代码
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
childWidth = child.getMeasuredWidth();
childHeight  = child.getMeasuredHeight();

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

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

复制代码
setMeasuredDimension(width, height);

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

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

复制代码
child.layout(childLeft , childTop,
        childLeft+childWidth, childTop+ childHeight);

具体的代码实现

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

小结

相关推荐
砖厂小工6 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心7 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心7 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker9 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴9 小时前
Android17 为什么重写 MessageQueue
android
阿巴斯甜1 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker1 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95271 天前
Andorid Google 登录接入文档
android
黄林晴1 天前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab2 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读