使用ViewTreeObserver测量View的宽高
2019-10-10 本文已影响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);
}
});
}