最近项目中有个UI需求:动态为radiogroup添加radiobutton ,一行显示两个。
1.为了定义radiogroup的布局,重新写了radiogroup的布局
FlowRadioGroup.java
package com.example.myui.components;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.RadioGroup;
public class FlowRadioGroup extends RadioGroup {
public FlowRadioGroup(Context context) {
super(context);
}
public FlowRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
int childCount = getChildCount();
int x = 0;
int y = 0;
int row = 0;
Log.e("FlowRadioGroup", "maxWidth=" + maxWidth);
for (int index = 0; index < childCount; index++) {
final View child = getChildAt(index);
if (child.getVisibility() != View.GONE) {
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
// 此处增加onlayout中的换行判断,用于计算所需的高度
int width = maxWidth/2; //一行显示2个
int height = child.getMeasuredHeight();
x += width;
y = row * height + height;
if (x > maxWidth-10) {
x = width;
row++;
y = row * height + height;
}
}
}
// 设置容器所需的宽度和高度
setMeasuredDimension(maxWidth, y);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int childCount = getChildCount();
Log.e("FlowRadioGroup", "childCount=" + childCount);
int maxWidth = r - l;
int x = 0;
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 = maxWidth/2; 一行显示2个
//调间距 默认的基础上加了20
int height = child.getMeasuredHeight()+ 20;
x += width;
y = row * height + height;
if (x > maxWidth) {
x = width;
row++;
y = row * height + height;
}
child.layout(x - width, y - height, x, y);
}
}
}
}
用法实例
myradiogroup = (FlowRadioGroup) findViewById(R.id.myradiogroup);
for(int i=0; i<10; i++)
{
RadioButton tempButton = new RadioButton(this);
// tempButton.setPadding(0, -10, 0, 0); // 设置文字距离按钮四周的距离
tempButton.setText("按钮 " + i);
tempButton.setGravity(Gravity.BOTTOM);
tempButton.setTextSize(24);
myradiogroup.addView(tempButton, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
效果图