RadioGroup自动换行(拿前辈的进行更改)

本文介绍了一种自定义Android RadioGroup的方法,通过重写onMeasure和onLayout方法实现灵活的子视图排列。该方法允许RadioGroup内的按钮按需换行,并确保不会超出父容器的最大宽度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义View集成RadioGroup,重写onMeasure和onLayout。
下面贴出两个函数的代码:
         @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取最大宽度
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
//获取Group中的Child数量
int childCount = getChildCount();
//设置Group的左边距,下面也会使用x计算每行所占的宽度
int x = 0;
//设置Group的上边距,下面也会使用y计算Group所占的高度
int y = 30;
//设置Group的行数
int row = 0;
for (int index = 0; index < childCount; index++) {
final View child = getChildAt(index);
if (child.getVisibility() != View.GONE) {
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
//重新计算child的宽高
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
//添加到X中,(width+10) 设置child左边距
x += (width + 10);
//行数*child高度+这次child高度=现在Group的高度,(height + 10)设置child上边距
y = row * (height + 10) + (height + 10);
//当前行宽X大于Group的最大宽度时,进行换行
if (x > maxWidth) {
//当index不为0时,进行row++,防止FirstChild出现大于maxWidth时,提前进行row++
if (index != 0)
row++;
//child的width大于maxWidth时,重新设置child的width为最大宽度
if (width >= maxWidth) {
width = maxWidth - 30;
}
//重新设置当前X
x = (width + 20);
//重新设置现在Group的高度
y = row * (height + 10) + (height + 10);
}
}
}
// 设置容器所需的宽度和高度
setMeasuredDimension(maxWidth, y);
}



         @Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int childCount = getChildCount();
int maxWidth = r - l;
int x = 10;
int y = 0;
int row = 0;
for (int i = 0; i < childCount; i++) {
final View child = this.getChildAt(i);
if (child.getVisibility() != View.GONE) {
int width = child.getMeasuredWidth();
int height = child.getMeasuredHeight();
x += (width + 10);
y = row * (height + 10) + (height + 10);
if (x > maxWidth) {
if (i != 0)
row++;
if (width >= maxWidth) {
width = maxWidth - 30;
}
x = (width + 20);
y = row * (height + 10) + (height + 10);
}
child.layout(x - width, y - height, x, y);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值