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

小结

相关推荐
モンキー・D・小菜鸡儿11 小时前
Android 中 StateFlow 的使用
android·kotlin
二川bro11 小时前
字符串特性解析:Python不可变性引发的错误
android·开发语言·python
2501_9371549311 小时前
酷秒神马 9.0 2025 版:微服务架构
android·源码·源代码管理·机顶盒
少年张二狗11 小时前
Vue + Element-UI 图片上传实现拖拽排序功能
前端·vue.js·ui
我又来搬代码了11 小时前
【Android】【Compose】Compose知识点复习(一)
android·前端·kotlin·android studio
fatiaozhang952711 小时前
九联UNP-SJA8-国科GK6323V100C-2+8G-安卓9.0-原厂强刷固件包-可救砖及开ADB教程
android·adb·电视盒子·刷机固件·机顶盒刷机·机顶盒刷机固件·九联unp-sja8
似霰12 小时前
传统 Hal 开发笔记4----实现 Hal 模块
android·hal
Android出海12 小时前
Google Play正式出手整治后台耗电应用
android·新媒体运营·产品运营·流量运营·用户运营
Winter_Sun灬12 小时前
CentOS7 交叉编译 ACE+TAO-6.5.13 安卓 arm64-v8a 静态库
android·ace
Digitally12 小时前
4种有效方法:如何将音乐从Mac传输到Android
android