效果图:

步骤
- 自定义RadioGroup
- 改写onMeasure()
原理
- 测量子view的大小,如果单行宽度超出屏幕宽度,则将这个子view做换行处理。
- 这里用到的换行方式可能和别人不同,网上的大部分代码都是在RadioGroup中嵌入多行LinearLayout,这里用的方式是改变子view的margin。
- 换行处理就是将该view的marginTop变成上一行的高度,marginLeft变成负的,具体数值是上一行的宽度。ps:只需要将每行第一个设置marginLeft。
还有些话:
这种方法无法保留子view在xml中原有的margin,原因是我没找到在代码中获取margin的方法,如果有大神知道,希望能留言告诉我。
下面就是代码了。
代码
public class CustomRadioGroup extends RadioGroup {
public CustomRadioGroup(Context context) {
super(context);
}
public CustomRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
super.addView(child, index, params);
}
@Override
public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
super.setOnCheckedChangeListener(listener);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int lineWidth = 0;//用于记录宽度是否超出,超出时归零
int totalLineHeight = 0;//用于记录已有内容的高度,用于放置下一行时使用
int lineHeight = 0;//用于记录已有内容的高度,用于放置下一行时使用
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
measureChild(child,widthMeasureSpec, heightMeasureSpec);
int factWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();//radioGroup中可用的宽度
if ((lineWidth + child.getMeasuredWidth()+10) > factWidth) {
lineHeight = totalLineHeight;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(child.getLayoutParams());
params.setMargins( -lineWidth, lineHeight, 0, 0);
child.setLayoutParams(params);
totalLineHeight += child.getMeasuredHeight();
lineWidth = 0;
lineWidth += child.getMeasuredWidth();
} else {
lineWidth += child.getMeasuredWidth();
int childBottom = (int) (child.getY() + child.getMeasuredHeight());
if (totalLineHeight < childBottom) {
totalLineHeight = childBottom;
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(child.getLayoutParams());
if(lineHeight == 0) {
params.setMargins(0, lineHeight, 0, 0);
}else {
params.setMargins(10, lineHeight, 0, 0);
lineWidth+=10;
}
child.setLayoutParams(params);
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}