RadioGroup 的分列换行

最近项目中有个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);
  }

效果图

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值