use onLayout implements LinearLayout in vertical orientation

矫情吗;* 2023-10-17 17:49 136阅读 0赞

use onLayout implements LinearLayout in vertical orientation

  1. import android.content.Context;
  2. import android.util.AttributeSet;
  3. import android.view.View;
  4. import android.view.ViewGroup;
  5. public class MyLayout extends ViewGroup {
  6. public MyLayout(Context context, AttributeSet attrs) {
  7. super(context, attrs);
  8. }
  9. //onMeasure被Android在onLayout之前调用。
  10. @Override
  11. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  12. //所有子View加起来总的高度和宽度。
  13. int measuredWidth = 0;
  14. int measuredHeight = 0;
  15. int count = getChildCount();
  16. for (int i = 0; i < count; i++) {
  17. View v = this.getChildAt(i);
  18. if (v.getVisibility() != View.GONE) {
  19. this.measureChild(v, widthMeasureSpec, heightMeasureSpec);
  20. measuredWidth = Math.max(measuredWidth, v.getMeasuredWidth());
  21. measuredHeight += v.getMeasuredHeight();
  22. }
  23. }
  24. //仔细检查!不要疏忽掉一些padding的值。
  25. measuredWidth += getPaddingLeft() + getPaddingRight();
  26. measuredHeight += getPaddingTop() + getPaddingBottom();
  27. this.setMeasuredDimension(measuredWidth, measuredHeight);
  28. }
  29. // Android系统在onMeasure之后调用onLayout。
  30. @Override
  31. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  32. // 在left,top,right,bottom这四个坐标参数“框”出来一个盛放子View的矩形空间,在此空间内一个一个摆放子View。
  33. int count = this.getChildCount();
  34. for (int i = 0; i < count; i++) {
  35. View v = getChildAt(i);
  36. if (v.getVisibility() != View.GONE) {
  37. int childHeight = v.getMeasuredHeight();
  38. //在细分的(left, top, right, top + childHeight)框出来的矩形空间内摆放这一子View。
  39. v.layout(left, top, right, top + childHeight);
  40. //把顶点的锚定位置往下移。
  41. top = top + childHeight;
  42. }
  43. }
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读