关于onMeasure()方法和onLayout()方法感悟

本文探讨了在XML布局中已设定大小参数的情况下,如何利用Java代码中的onMeasure()方法获取视图组件的实际尺寸,并通过onLayout()方法来设置视图的位置及大小,确保Canvas绘图工具能正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<当你在xml布局中,已经设置了大小参数的时候,如果需要canvas画图工具实现显示效果,此时,需要用onMeasure()方法得到java代码中需要的宽高,然后进行绘制,有一个地方我不太明白,就是很多博客上都说需要调用setMeasuredDimension()方法,但是我没有用到这个,我在onLayout()里面设置了位置和大小。附上代码:

@Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  // 得到mHeaderViewz的宽、高
  if (mHeaderView != null) {
   
   //设置mHeaderView的宽度和高度
   measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec);
   mHeaderViewWidth = mHeaderView.getMeasuredWidth();
   mHeaderViewHeight = mHeaderView.getMeasuredHeight();
   
  }
 }
//onLayout()方法的作用是继承自View,当布局发生改变时调用
 @Override
 protected void onLayout(boolean changed, int left, int top, int right,
   int bottom) {
  super.onLayout(changed, left, top, right, bottom);
  if (mHeaderView != null) {
   mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
   configureHeaderView(getFirstVisiblePosition());
   //getFirstVisiblePosition()返回显示在屏幕上的第一个元素在适配器中所处的位置。
  }
 }

另外附上别人的一些研究和分析:

http://blog.youkuaiyun.com/az44yao/article/details/8272215

 

第一次写博客,希望能坚持下来
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值