wilkas wilkas - 1 month ago 7
Android Question

`getLeft()` returns zero in `onWindowFocusChanged()`

I have a separate class

Answer
which extends
ImageView
. This object is programatically added to the container view and then position initialisation method is called in
onWindowFocusChanged()
- this method sets correct margins and layout parameters and turns visibility on. Then I try to get Answer's initial X position by calling
getLeft()
. No matter if this is called from within Answers class
this.getLeft()
or from main activity
answer_object1.getLeft()
it still returns zero.

Why is that?

If I add Image view via XML and call 'getLeft()' in
onWindowFocusChanged()
it returns correct value.

Answer

getLeft() will return you the actual value only after layout step will complete and onLayout of your Answer will be called. So, to record the initial position of your view it's better to do so in onLayout.

Now speaking of onWindowFocusChanged() - documentation makes no promises on whether this method will be called before onLayout or after, so it is not the best place to record the initial position of your view.

Comments