Android自定义控件的onMeasure和onLayout

public class MultiViewGroup extends ViewGroup {

 private Context mContext;

 private static String TAG = "MultiViewGroup";

 public MultiViewGroup(Context context) {
  super(context);
  mContext = context;
  init();
 }

 public MultiViewGroup(Context context, AttributeSet attrs) {
  super(context, attrs);
  mContext = context;
  init();
 }

 private void init() {
  // 初始化3个 LinearLayout控件
  LinearLayout oneLL = new LinearLayout(mContext);
  oneLL.setBackgroundColor(Color.RED);
        addView(oneLL);
  
  LinearLayout twoLL = new LinearLayout(mContext);
  twoLL.setBackgroundColor(Color.YELLOW);
  addView(twoLL);
  
  LinearLayout threeLL = new LinearLayout(mContext);
  threeLL.setBackgroundColor(Color.BLUE);
  addView(threeLL);
 }

 // measure过程
 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

  Log.i(TAG, "--- start onMeasure --");

  // 设置该ViewGroup的大小
  int width = MeasureSpec.getSize(widthMeasureSpec);
  int height = MeasureSpec.getSize(heightMeasureSpec);
  setMeasuredDimension(width, height);//这里必须要有的,否则会有异常

  int childCount = getChildCount();
  Log.i(TAG, "--- onMeasure childCount is -->" + childCount);
  for (int i = 0; i < childCount; i++) {
   View child = getChildAt(i);
   // 设置每个子视图的大小 , 即全屏
   child.measure(MultiScreenActivity.screenWidth, MultiScreenActivity.scrrenHeight);
  }
 }

 // layout过程
 @Override
 protected void onLayout(boolean changed, int l, int t, int r, int b) {
  // TODO Auto-generated method stub
  Log.i(TAG, "--- start onLayout --");
  int startLeft = 0; // 每个子视图的起始布局坐标
  int startTop = 10; // 间距设置为10px 相当于 android:marginTop= "10px"
  int childCount = getChildCount();
  Log.i(TAG, "--- onLayout childCount is -->" + childCount);
  for (int i = 0; i < childCount; i++) {
   View child = getChildAt(i);
   child.layout(startLeft, startTop,
     startLeft + MultiScreenActivity.screenWidth,
     startTop + MultiScreenActivity.scrrenHeight);
   startLeft = startLeft + MultiScreenActivity.screenWidth ; //校准每个子View的起始布局位置
   //三个子视图的在屏幕中的分布如下 [0 , 320] / [320,640] / [640,960]
  }
 }

}

onMeasure测量View的大小,child.measure(MultiScreenActivity.screenWidth, MultiScreenActivity.scrrenHeight);测量child的宽和高

onLayout放置view相对屏幕左上角的距离child.layout(startLeft, startTop,
     startLeft + MultiScreenActivity.screenWidth,
     startTop + MultiScreenActivity.scrrenHeight);这里的参数是child的起点坐标(x,y)左上角,后边是child结束坐标(x,y)右下角

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值