为什么在无效后直接调用requestLayout [英] Why is requestLayout being called directly after invalidate

查看:136
本文介绍了为什么在无效后直接调用requestLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习自定义视图,并想了解invalidate()requestLayout().

I'm learning about custom views and wanted to learn about invalidate() and requestLayout().

请参考此答案及其图表:

Please refer to this answer and its diagram:

https://stackoverflow.com/a/25846243/4243687

invalidate()告诉Android,视图状态已更改,需要重新绘制.

invalidate() tells Android that the state of the view has changed and needs to be re-drawn.

requestLayout()表示视图的大小可能已更改,需要重新测量,然后重新绘制.

requestLayout() means the size of the view may have changed and needs to be remeasured, and then re-drawn.

invalidate()将调用dispatchDraw()draw()onDraw(),因此它将重新呈现视图.

invalidate() will invoke dispatchDraw(), draw(), and onDraw() hence it re-renders the view.

requestLayout()几乎完成了从测量到再次渲染的所有工作.

requestLayout() on the other hand does pretty much everything from measuring to re-rendering again.

为什么这么多示例(甚至是TextView源代码)都调用invalidate(),然后在下一行直接调用requestLayout()?

Why do so many of the examples out there (even the TextView source code) call invalidate() and then requestLayout() right on the next line?

推荐答案

invalidate()专用于重绘视图的内容.重绘不会同步发生.而是将视图区域标记为无效,以便在下一个渲染周期中重新绘制该视图.

invalidate() is used specifically for redrawing the content of your view. The redraw does not happen synchronously. Instead, it flags the region of your view as invalid so that it will be redrawn during the next render cycle.

requestLayout()中的某些内容可能更改了尺寸时,应使用

requestLayout().在这种情况下,父视图和视图层次结构中的所有其他父视图都需要通过布局传递来重新调整自身.

requestLayout() should be used when something within it has possibly changed its dimensions. In this case, the parent view and all other parents up the view hierarchy will need to readjust themselves via a layout pass.

如果您没有对视图进行任何会改变其大小的操作,则不必调用requestLayout().

If you are not doing anything to your view that would change its size, then you do not have to call requestLayout().

如果您回头查看TextView的代码中调用requestLayout()的位置,它将位于影响视图范围的方法上.例如setPadding()setTypeface()setCompoundDrawables()

If you go back and look at the places in the code for TextView where requestLayout() is being called, it will be on methods where the view's bounds will be affected. For example, setPadding(), setTypeface(), setCompoundDrawables(), etc.

因此,当调用requestLayout()时,应将其与调用配对以使无效,以确保重新绘制整个视图.

So, when requestLayout() is called, it should be paired with a call to invalidate to ensure that the entire view is redrawn.

这篇关于为什么在无效后直接调用requestLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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