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 代码实现:可换行的布局控件

小结

相关推荐
范特西林19 分钟前
代码的生成:AIDL 编译器与 Parcel 的序列化艺术
android
范特西林20 分钟前
深入内核:Binder 驱动的内存管理与事务调度
android
范特西林1 小时前
解剖麻雀:Binder 通信的整体架构全景图
android
范特西林1 小时前
破冰之旅:为什么 Android 选择了 Binder?
android
奔跑中的蜗牛6663 小时前
一次播放器架构升级:Android 直播间 ANR 下降 60%
android
测试工坊5 小时前
Android 视频播放卡顿检测——帧率之外的第二战场
android
Kapaseker6 小时前
一杯美式深入理解 data class
android·kotlin
鹏多多6 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter
Carson带你学Android6 小时前
OpenClaw移动端要来了?Android官宣AI原生支持App Functions
android
黄林晴6 小时前
Android 删了 XML 预览,现在你必须学 Compose 了
android