美文网首页
使用ViewTreeObserver测量View的宽高

使用ViewTreeObserver测量View的宽高

作者: 好学人 | 来源:发表于2019-10-10 00:42 被阅读0次

ViewTreeObserver

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 View#getViewTreeObserver() for more information.

OnGlobalLayoutListener

Interface definition for a callback to be invoked when the global layout state or the visibility of views within the view tree changes.

测量View的宽高

/**
 * 使用ViewTreeObserver测量View的宽高
 */
public void getLayoutWidth(final View view) {
    view.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    int width = BitmapActivity.this.bitmapImageView.getWidth();
                    int height = BitmapActivity.this.bitmapImageView.getHeight();
                    Log.i("Haoxueren", "onGlobalLayout: " + width + ":" + height);
                    view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
}

相关文章

网友评论

      本文标题:使用ViewTreeObserver测量View的宽高

      本文链接:https://www.haomeiwen.com/subject/qognpctx.html