ViewTreeObserver中的OnGlobalLayoutListener

时间:2019-03-25
本文章向大家介绍ViewTreeObserver中的OnGlobalLayoutListener,主要包括ViewTreeObserver中的OnGlobalLayoutListener使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
/**
 * A view tree observer is used to register listeners that can be notified of global
 * changes in the view tree. Such global events include, but are not limited to,
 * layout of the whole tree, beginning of the drawing pass, touch mode change....
 *
 * A ViewTreeObserver should never be instantiated by applications as it is provided
 * by the views hierarchy. Refer to {@link android.view.View#getViewTreeObserver()}
 * for more information.
 */
public final class ViewTreeObserver

ViewTreeObserver类用来注册各种view tree变化的监听。

/**
 * 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 {
    /**
     * Callback method to be invoked when the global layout state or the visibility of views
     * within the view tree changes
     */
    public void onGlobalLayout();
}

OnGlobalLayoutListener 接口:

当全局布局状态或视图树中视图的可见性发生更改时,将调用的回调的接口定义。

一般来说,在onCreate时我们是无法拿到View的高度和宽度的,可以听过监听这个接口来获取高度和宽度,或者做一些View的动画处理之类的。

itemsView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			
    @Override
    public void onGlobalLayout() {
        itemsView.postDelayed(runnable, 10);
        itemsView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});