I have an Activity that displays various fragments using the supportFragmentManager. When I attempt to get a view in the fragment or the parent activity for that matter, and attempt to measure it's position on the screen it only seems to be available for measurement sometime after onResume in the fragment lifecycle or after onActivityCreated/onResume/onAttachedToWindow in the Activity. Typically it is available after about 100-200ms. Is there any lifecycle event documented/undocumented or solid method of knowing when this has occurred, like maybe a canvas drawing event. The fragment in question needs to measure a parent activity view, but it isn't always available in onResume right away. I really hate having to do some kind of hack like having a handler wait 200ms.
Asked
Active
Viewed 675 times
1 Answers
1
You can use ViewTreeObserver.addOnGlobalLayoutListener().
@Override
public void onCreate(Bundle savedInstanceState) {
//...
someView.getViewTreeObserver().addOnGlobalLayoutListener(getOnLayoutListener(someView));
//...
}
private ViewTreeObserver.OnGlobalLayoutListener getOnLayoutListener(final View unHookView) {
return new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
unHookView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
else
unHookView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//YOUR CODE HERE
}
};
}

Gero
- 1,842
- 25
- 45
-
Will give it a shot. Tks. – Peter Birdsall Jul 28 '16 at 01:22
-
Really close, the listener seems to want to persist in the fragment even if removing in the fragment onPause and/or onDetach causing the activity to abort in onDestroy due to the listener hanging around, since I'm looking at an Activity view, will have to look at it further. The info for the view is available for the view in the fragment. :) – Peter Birdsall Jul 28 '16 at 03:24
-
@PeterBirdsall the listener is being removed just inside the `onGlobalLayout` method.. so it will be removed immediatly after layout is done. If you are facing a race condition with quick fragment adds and removals, you can check if fragment is still added inside `onGlobalLayout()` using the condition `YourFragment.this.isAdded()` – Gero Jul 28 '16 at 13:22
-
@PeterBirdsall also, if you are using this process on Fragments and not on Activities, you should be adding `someView.getViewTreeObserver().addOnGlobalLayoutListener...` inside `Fragment.onCreateView` instead of `Fragment.onCrete` – Gero Jul 28 '16 at 13:25