前段时间公司项目要求有一个自动换行的RadioGroup,作为一个资深的Android小菜鸟,表示做不到啊~~~。
后来在网上看到了人家写的自定义LinearLayout,然后参考着人家的代码,进行了自己的修改就拿来用了。下面附上代码,
public class MyRadioGroup extends RadioGroup {
private int mL, mR, mT, mB;
private Hashtable<View, Position> map = new Hashtable<View, Position>();
private final static int DEFAULT_COL = 10;
// 上下间距
private final int mline = 10;
// 左右间距
private int mCol = DEFAULT_COL;
public MyRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyRadioGroup(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int mwidth = MeasureSpec.getSize(widthMeasureSpec);
int mcount = getChildCount();
mL = 0;
mR = 0;
mT = 5;
mB = 0;
int j = 0;
boolean isFirstRow = true;// 第一行
for (int i = 0; i < mcount; i++) {
final View childView = getChildAt(i);
// MeasureSpec.UNSPECIFIED(未指定尺寸)
childView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
// onlayout中的换行判断,用于计算所需要的高度
int childw = childView.getMeasuredWidth();
int childh = childView.getMeasuredHeight();
mR += childw;// 讲每次添加的子控件宽度叠加,大于设定的高度就换行,高度也要重置。
Position position = new Position();
mL = getPosition(i - j, i);
mR = mL + childView.getMeasuredWidth();
if (mR >= mwidth) {// 超过一行就要换行,同时对每个控件的间隙平均分配
if (isFirstRow) {
mCol = (int) ((mwidth - childView.getMeasuredWidth() * i
* 1.0)
/ (i + 1) + 0.5);
isFirstRow = false;
for (int k = 0; k < i; k++) {
View tempChild = getChildAt(k);
Position position2 = map.get(tempChild);
position2.left += mCol - DEFAULT_COL;
position2.right += mCol - DEFAULT_COL;
}
}
j = i;
mL = getPaddingLeft() + mCol - DEFAULT_COL;
mR = mL + childView.getMeasuredWidth();
mT += childh + mline;
}
mB = mT + childView.getMeasuredHeight();
position.left = mL;
position.top = mT;
position.right = mR;
position.bottom = mB;
map.put(childView, position);
}
// setMeasuredDimension()决定了自定义View的大小
setMeasuredDimension(mwidth, mB + getPaddingBottom());
}
@Override
protected android.widget.LinearLayout.LayoutParams generateDefaultLayoutParams() {
// TODO Auto-generated method stub
return new LayoutParams(1, 1);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
Position position = map.get(child);
if (position != null) {
child.layout(position.left, position.top, position.right,
position.bottom);
} else {
}
}
}
private class Position {
int left, top, right, bottom;
}
public int getPosition(int IndexInRow, int childIndex) {
if (IndexInRow > 0) {
return getPosition(IndexInRow - 1, childIndex - 1)
+ getChildAt(childIndex - 1).getMeasuredWidth() + mCol;
}
return getPaddingLeft();
}
}