I am trying to do calculate view's x,y positions after completion of loading of activity. What I did is view.postDelayed(runnable, 2000)
which is working fine. code reviewer is not happy with this and suggested to use OnGlobalLayoutListener to know about the completion of activity loading. Somehow I don't like OnGlobalLayoutListener because it is associated with entire view tree which is not required for my solution. I am trying to understand pros and cons of these approaches. Thanks!
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
If all you are trying to do is read the view's
x
andy
coordinates, I recommend usingview.post(Runnable)
with no delay (unless there is a good reason to include a delay). This will add theRunnable
to a message queue to in the UI thread. TheRunnable
will wait to execute until after yourView
is inflated and attached to the window. SinceView
position property values depend on the view's layout context, posting aRunnable
will give you the timing that you are looking for.As you mentioned in your question description, an
OnGlobalLayoutListener
will apply to the entireView
's layout as the class name suggests. AnOnGlobalLayoutListener
should only be considered if you are concerned with the layout state or visibility of any or all views within the view tree. I.e. anything that causes the view tree to be re-laid out.Code reviewer is not happy because you wait 2s and guess that the loading of the activity is finished by then. This may be the case with your emulator or device but on older and slower devices the activity may not have finished loading. To be 100% safe that the activity has finished loading you should use the listener to inform the 'listener' when loading is completed.
I think that the correct way of doing this is by adding an onPreDrawListener to the view. This is the listener that is called when the view is about to be drawn, and where you already have all the information about it's size (width and height) and position (X and Y).
Example:
Don't forget to make the method onPreDraw return true, I don't know why but Android Studio makes it return false when you create the listener. Also don't forget to remove the listener from the view, otherwise it might be uselessly called again.