最近项目中需要实现一个GridView显示6*5=30项,并铺满整个界面,界面中还有自定义ActionBar等其他控件,所以需要获取剩下屏幕的高度。通过百度得知View有一个监听函数,亲测使用有效,特此记录,方便日后查阅。
gv_test.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//给GridView设置Adapter,在adapter的getView中获取GridView的高度,在这个回调之前获取的高度都是0
//处理完后remove掉,至于为什么,后面有解释
gv_test.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
});
通过源码追溯进去,找到ViewTreeObserver这个类,里面有很多interface,都是用来追踪View的各种状态变化的。
找到OnGlobalLayoutListener
/**
* Interface definition for a callback to be invoked when the global layout state
* or the visibility of views within the view tree changes.
*/
public interface OnGlobalLayoutListener {