9

Calling getLocationOnScreen() on an ImageView (or other View) in a response to a button click gives correct values.

But when calling getLocationOnScreen() from Activity::onCreate(), I only get [0, 0]. How can I fix this?

Is onCreate() too early for all calculations to be done? Is there a later better place to hook to start animations?

Jonny
  • 15,955
  • 18
  • 111
  • 232
  • 1
    what are your goal?to create an starting point for an animation?? – Niko Adrianus Yuwono Nov 06 '12 at 03:34
  • Using the code in http://stackoverflow.com/a/10542153/129202 as an example. It moves views to center of screen with push of a button. If the same cycle is caused already in onCreate, it doesn't work as view.getLocationOnScreen() returns empty values. – Jonny Nov 06 '12 at 03:37
  • @NikoAdrianusYuwono yeah actually I have same question. I am trying to animate my ProgressBar when it scroll my RecyclerView. I want it to animate when its start sowing till the middle of the screen. – Irfan Yaqub Aug 12 '21 at 19:28

1 Answers1

27

It's too early to check for getLocationOnScreen() in onCreate(). The better place is at view level (if you are using custom views), is at onLayout(). Only here, the view's size and position are calculated. In case, you aren't creating custom views, you could obtain it in activity level at onWindowFocusChanged() (with the activity having the focus).

sriramramani
  • 1,088
  • 1
  • 9
  • 8
  • 1
    Thanks, I was able to find the same answer `onWindowFocusChanged()` from http://stackoverflow.com/a/6560726/129202 I'd say the reference http://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[]) is a bit too hush hush on these common pitfalls that a lot of people seem to have. – Jonny Nov 06 '12 at 04:04