您的位置:首页 > 移动开发 > Android开发

android.view.ViewTreeObserver.addOnGlobalLayoutListener

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

类似:

// This listener is used to get the final width of the GridView and then calculate the
// number of columns and the width of each column. The width of each column is variable
// as the GridView has stretchMode=columnWidth. The column width is used to set the height
// of each view so we get nice square thumbnails.
<pre name="code" class="java">mGridView.getViewTreeObserver().addOnGlobalLayoutListener( //view 布局完成时调用,每次view改变时都会调用
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (mAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(
mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
final int columnWidth =
(mGridView.getWidth() / numColumns) - mImageThumbSpacing;
mAdapter.setNumColumns(numColumns);   //设置 列数
mAdapter.setItemHeight(columnWidth);  //设置 高度
getViewTreeObserver().removeGlobalOnLayoutListener(this);

}
}
}
});




在gridview布局完成后,根据girdview的宽和高设置adapter列数和每个item高度

但是需要注意的是OnGlobalLayoutListener可能会被多次触发,因此在得到了高度之后,要将OnGlobalLayoutListener注销掉。

除了OnGlobalLayoutListener ,ViewTreeObserver还有如下内部类:

interface ViewTreeObserver.OnGlobalFocusChangeListener

当在一个视图树中的焦点状态发生改变时,所要调用的回调函数的接口类

interface ViewTreeObserver.OnGlobalLayoutListener

当在一个视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变时,所要调用的回调函数的接口类

interface ViewTreeObserver.OnPreDrawListener

当一个视图树将要绘制时,所要调用的回调函数的接口类

interface ViewTreeObserver.OnScrollChangedListener

当一个视图树中的一些组件发生滚动时,所要调用的回调函数的接口类

interface ViewTreeObserver.OnTouchModeChangeListener

当一个视图树的触摸模式发生改变时,所要调用的回调函数的接口类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐