Just in addition to the above answers, for the question where and when you should call getLocationOnScreen
?
For any information that is related to the view
, will be available only after the view has been laid out(created) on the screen. So to get the location put your code inside view.post(Runnable)
which is called after view
has been laid out, like this:
view.post(new Runnable() {
@Override
public void run() {
// This code will run when view created and rendered on screen
// So as the answer to this question, you can put the code here
int[] location = new int[2];
myView.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
}
});