[关闭]
@wangwangheng 2015-02-10T02:17:29.000000Z 字数 1368 阅读 2011

RadioGroup流式布局

自定义View


  1. import android.content.Context;
  2. import android.util.AttributeSet;
  3. import android.view.View;
  4. import android.view.View.MeasureSpec;
  5. import android.widget.RadioGroup;
  6. public class FlowRadioGroup extends RadioGroup {
  7. public FlowRadioGroup(Context context) {
  8. super(context);
  9. }
  10. public FlowRadioGroup(Context context, AttributeSet attrs) {
  11. super(context, attrs);
  12. }
  13. @Override
  14. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  15. int maxWidth = MeasureSpec.getSize(widthMeasureSpec);
  16. int childCount = getChildCount();
  17. int x = 0;
  18. int y = 0;
  19. int row = 0;
  20. for (int index = 0; index < childCount; index++) {
  21. final View child = getChildAt(index);
  22. if (child.getVisibility() != View.GONE) {
  23. child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
  24. // 此处增加onlayout中的换行判断,用于计算所需的高度
  25. int width = child.getMeasuredWidth();
  26. int height = child.getMeasuredHeight();
  27. x += width;
  28. y = row * height + height;
  29. if (x > maxWidth) {
  30. x = width;
  31. row++;
  32. y = row * height + height;
  33. }
  34. }
  35. }
  36. // 设置容器所需的宽度和高度
  37. setMeasuredDimension(maxWidth, y);
  38. }
  39. @Override
  40. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  41. final int childCount = getChildCount();
  42. int maxWidth = r - l;
  43. int x = 0;
  44. int y = 0;
  45. int row = 0;
  46. for (int i = 0; i < childCount; i++) {
  47. final View child = this.getChildAt(i);
  48. if (child.getVisibility() != View.GONE) {
  49. int width = child.getMeasuredWidth();
  50. int height = child.getMeasuredHeight();
  51. x += width;
  52. y = row * height + height;
  53. if (x > maxWidth) {
  54. //if (i==2) {
  55. x = width;
  56. row++;
  57. y = row * height + height;
  58. }
  59. child.layout(x - width, y - height, x, y);
  60. }
  61. }
  62. }
  63. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注