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

小结

相关推荐
运维_攻城狮38 分钟前
遇到liunx服务器IO负载,读IO流量峰值347MB/s,排查并解决。
android·运维·服务器·mysql
m0_748232391 小时前
qwenvl 以及qwenvl 2 模型架构理解
android·前端·后端
web136885658712 小时前
PHP For 循环
android·java·php
Neo Evolution2 小时前
每天一个Flutter开发小项目 (6) : 表单与验证的专业实践 - 构建预约应用
android·开发语言·前端·javascript·flutter
小墙程序员2 小时前
Android Framework 面试系列(四)Activity 启动原理
android
m0_748248773 小时前
Spring Boot 3.x 引入springdoc-openapi (内置Swagger UI、webmvc-api)
spring boot·后端·ui
和道一文字yyds3 小时前
MySQL 中如何解决深度分页的问题?什么是 MySQL 的主从同步机制?它是如何实现的?如何处理 MySQL 的主从同步延迟?
android·数据库·mysql
KdanMin3 小时前
Android SystemUI深度定制实战:下拉状态栏集成响铃功能开关全解析
android
黄大包3 小时前
解决安卓recyclerView滚到底部不彻底问题
android·滚动·recycleview·抖动
胖虎13 小时前
Android 布局系列(四):ConstraintLayout 使用指南
android·xml·布局·constraint·约束布局