Skip to content

Instantly share code, notes, and snippets.

@pokk
Created May 29, 2017 09:09
Show Gist options
  • Save pokk/a200cd0a9f007370aeead80471c52702 to your computer and use it in GitHub Desktop.
Save pokk/a200cd0a9f007370aeead80471c52702 to your computer and use it in GitHub Desktop.
Awaring a view is on measured or drawed by ViewTreeObserver

Introduction

If you can control your view size, for example as loading an imageview. You observe it then you can get the view size after the image is downloaded. You don't have to worry about when it is drawed and measured.

Example

OnCreate()

In Kotlin code:

this.view.let {
    it.viewTreeObserver.addOnGlobalLayoutListener {
        val height: Int = it.measuredHeight
        val width: Int = it.measuredWidth
    }
}

In Java code:

ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // You should remove the listener here because this listener will be trigger many times.
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        final int w = view.getMeasuredWidth();
        final int h = view.getMeasuredHeight();
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment