프로그래밍언어/Android

View - invalidate vs requestLayout difference (차이점)

유선생님의 코딩 교실 2019. 7. 9. 23:29

invalidate()

Calling invalidate() is done when you want to schedule a redraw of the view. It will result in onDraw being called eventually (soon, but not immediately). An example of when a custom view would call it is when a text or background color property has changed.

The view will be redrawn but the size will not change.

requestLayout()

If something about your view changes that will affect the size, then you should call requestLayout(). This will trigger onMeasure and onLayout not only for this view but all the way up the line for the parent views.

Calling requestLayout() is not guaranteed to result in an onDraw (contrary to what the diagram in the accepted answer implies), so it is usually combined with invalidate().

invalidate(); requestLayout();

An example of this is when a custom label has its text property changed. The label would change size and thus need to be remeasured and redrawn.

forceLayout()

When there is a requestLayout() that is called on a parent view group, it does not necessary need to remeasure and relayout its child views. However, if a child should be included in the remeasure and relayout, then you can call forceLayout() on the child. forceLayout() only works on a child if it occurs in conjunction with a requestLayout() on its direct parent. Calling forceLayout() by itself will have no effect since it does not trigger a requestLayout() up the view tree.

 

 

=> invalidate 와 requestLayout에 대해 정확한 차이를 몰랐다. 

invalidate는 ondraw를 반드시 호출하지만, 사이즈(width, height)를 지정하는 콜백인 onMeasure가 호출되진 않는다.

그래서 size가 변하지 않는다. 

 

request layout은 invalidate와 반대로 onMeasure 부터 불리지만, onDraw를 반드시 호출하진 않는다.

onMeasure가 호출 되므로 Size가 업데이트 된다.

그래서 2가지 조합으로 많이 사용한다.

 

 

참조: https://stackoverflow.com/questions/13856180/usage-of-forcelayout-requestlayout-and-invalidate