多列radiogroup

来源:互联网 发布:如何更改淘宝店铺名字 编辑:程序博客网 时间:2024/05/18 22:42

android SDK RadioGroup 继承LinearLayout 大家都知道 这个布局的特点,子布局线性排列,要么横要么竖, 现在呢,需要一个  类似gridview的 radiogroup,于是乎,就需要自定义RadioGroup ,重新测量、布局,进而达到下图效果

父布局是自定义的radiogroup  子布局是 sdk 默认的radiobutton 

自定义的 radiogroup 下面代码就是




直接上代码:


public class GridRadioGroup extends RadioGroup {


//子布局RadioButton 列数
private int column = 3;
//文字
private int textPaddingTB = 30;

private int margin = 30;
private int itemWidth;

public GridRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);

}


public GridRadioGroup(Context context) {
this(context, null);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int widthSize = MeasureSpec.getSize(widthMeasureSpec);

itemWidth = (widthSize - (column + 1) * margin) / column;

int childCount = getChildCount();

int itemHeight = 0;

for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.setPadding(0, textPaddingTB, 0, textPaddingTB);
child.measure(MeasureSpec.makeMeasureSpec(itemWidth, MeasureSpec.EXACTLY),
MeasureSpec.UNSPECIFIED);
itemHeight = child.getMeasuredHeight();
}

int rows = childCount % column == 0 ? childCount / column : childCount / column + 1;
int heightSize = rows * itemHeight + (rows + 1) * margin;
setMeasuredDimension(widthMeasureSpec, heightSize);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int rows = 0;
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();

int yu = i % column;
int cl, ct, cr, cb;
if(i >= column - 1 && yu == 0){
rows ++;
}

cl = margin * (yu + 1) + yu * width;
ct = margin * (rows + 1) + rows * height;
cr = margin * (yu + 1) + (yu + 1) * width;
cb = margin * (rows + 1) + (rows + 1) * height;
view.layout(cl, ct, cr, cb);
}
}

}

关注微信 dream_we90


0 0
原创粉丝点击