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.
问问题
601 次
1 回答
1
您可以使用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
}
};
}
于 2016-07-27T22:47:07.690 回答