View的绘制完成通知

有时候需要在onCreate方法中知道某个View组件的宽度和高度等信息,而直接调用View组件的getWidth()、getHeight()、getMeasuredWidth()、getMeasuredHeight()、getTop()、getLeft()等方法是无法获取到真实值的,只会得到0。这是因为View组件布局要在onResume回调后完成。下面提供实现方法,onGlobalLayout回调会在view布局完成时自动调用:


类似:

[java]  view plain copy
  1. // This listener is used to get the final width of the GridView and then calculate the  
  2. // number of columns and the width of each column. The width of each column is variable  
  3. // as the GridView has stretchMode=columnWidth. The column width is used to set the height  
  4. // of each view so we get nice square thumbnails.  
  5. mGridView.getViewTreeObserver().addOnGlobalLayoutListener( //view 布局完成时调用,每次view改变时都会调用  
  6.         new ViewTreeObserver.OnGlobalLayoutListener() {  
  7.             @Override  
  8.             public void onGlobalLayout() {  
  9.                 if (mAdapter.getNumColumns() == 0) {  
  10.                         final int numColumns = (int) Math.floor(  
  11.                                  mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));  
  12.                     if (numColumns > 0) {  
  13.                     <span style="white-space:pre">  </span>final int columnWidth =  
  14.                             (mGridView.getWidth() / numColumns) - mImageThumbSpacing;  
  15.                         mAdapter.setNumColumns(numColumns);   //设置 列数  
  16.                             mAdapter.setItemHeight(columnWidth);  //设置 高度  
  17.                     }  
  18.                 }  
  19.             }  
  20.         });  

在gridview布局完成后,根据girdview的宽和高设置adapter列数和每个item高度
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值