Skip to content

Instantly share code, notes, and snippets.

@s3va
Created August 28, 2022 20:28
Show Gist options
  • Save s3va/c684c53863ba73024c96e4c50a3038dd to your computer and use it in GitHub Desktop.
Save s3va/c684c53863ba73024c96e4c50a3038dd to your computer and use it in GitHub Desktop.
When can I View.getX() from View?
view.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Layout has happened here.
// Don't forget to remove your listener when you are done with it.
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
@s3va
Copy link
Author

s3va commented Aug 28, 2022

https://stackoverflow.com/a/32400275/11798617

ViewGroups such as RelativeLayout do not layout their children immediately, and thus your View does not yet know where it will lie on screen. You need to wait for the RelativeLayout to complete a layout pass before that can happen.

You can listen for global layout events like so:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment