onGlobalLayoutListener与postRunnable [英] onGlobalLayoutListener vs postRunnable

查看:51
本文介绍了onGlobalLayoutListener与postRunnable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在活动加载完成后计算视图的x,y位置.我所做的是view.postDelayed(runnable, 2000),它工作正常.代码审阅者对此不满意,建议使用OnGlobalLayoutListener来了解活动加载的完成情况.我不喜欢OnGlobalLayoutListener,因为它与整个视图树相关联,这对于我的解决方案不是必需的.我试图了解这些方法的利弊.谢谢!

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!

推荐答案

如果您要尝试做的就是读取视图的xy坐标,那么我建议不加延迟地使用view.post(Runnable)(除非存在包括延迟的充分理由).这会将Runnable添加到UI线程中的消息队列中. Runnable将等待执行,直到将View充气并连接到窗口之后.由于View位置属性值取决于视图的布局上下文,因此发布Runnable将为您提供所需的时间.

If all you are trying to do is read the view's x and y coordinates, I recommend using view.post(Runnable) with no delay (unless there is a good reason to include a delay). This will add the Runnable to a message queue to in the UI thread. The Runnable will wait to execute until after your View is inflated and attached to the window. Since View position property values depend on the view's layout context, posting a Runnable will give you the timing that you are looking for.

正如您在问题描述中所提到的,按照类名的建议,OnGlobalLayoutListener将应用于整个View的布局.仅当您担心视图树中任何或所有视图的布局状态或可见性时,才应考虑使用OnGlobalLayoutListener. IE.导致视图树重新布局的所有内容.

As you mentioned in your question description, an OnGlobalLayoutListener will apply to the entire View's layout as the class name suggests. An OnGlobalLayoutListener 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.

这篇关于onGlobalLayoutListener与postRunnable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆