I have a RelativeLayout
with lots of child views, and I want to calculate a position of one of them (relative to the parent container) once the activity is started.
My problem is that I cannot get any coordinates when I populate the layout with views, which happens in onStart
method of my activity. In particular, I tried every recipe mentioned in a similar question but didn't succeed; all these methods return just zeros.
Nevertheless, if I repeat the calculation later (i. e. in a button handler), they do calculate the proper position.
So my assumption is that onStart
is not a good place to calculate positions because something is not ready yet. But which place would be better? According to the docs, onStart
is the last call before the activity is displayed to the user. I tried moving my math into onResume
but that didn't help.
You can be sure that views have valid coordinates this way:
parentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// really important! elsewhere this method will be called continously
parentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
// do your job
}
});