首页 > 试题广场 >

请描述requestLayout,invalidate和po

[问答题]
请描述requestLayoutinvalidatepostInvalidate的异同。

1、invalidate()和requestLayout()主要用于视图的重绘和更新,区别如下:

invalidate()会执行onDraw()方法,即使什么都没有发生改变,它也会重新绘制。
requestLayout()会执行onMeasure()和onLayout()

所以我们进行视图更新的时候,若:

  • 视图的大小、位置发生了改变,而视图内容不变时,调用requestLayout()执行onMeasure()和onLayout()
  • 视图的大小、位置不变,而视图内容有变化时,调用invalidate()执行onDraw()
  • 视图大小或位置、内容均发生改变时、则需要同时调用requestLayout()和invalidate()

2、invalidate()和postInvalidate()均用于重新绘制视图,区别如下:

  • invalidate()用于在UI线程(主线程)中重新绘制视图
  • postInvalidate()会在非UI线程(异步线程)重新绘制视图,不用我们去调用handler
编辑于 2017-09-04 16:03:17 回复(0)

requestLayout

added in API level 1
void requestLayout ()

Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree. This should not be called while the view hierarchy is currently in a layout pass (isInLayout(). If layout is happening, the request may be honored at the end of the current layout pass (and then layout will run again) or after the current frame is drawn and the next layout occurs.

Subclasses which override this method should call the superclass method to handle possible request-during-layout errors correctly.


If you override this method you must call through to the superclass implementation.
invalidate
added in API level 1
void invalidate ()

Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future.

This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
postInvalidate
added in API level 1
void postInvalidate ()


Cause an invalidate to happen on a subsequent cycle through the event loop. Use this to invalidate the View from a non-UI thread.

This method can be invoked from outside of the UI thread only when this View is attached to a window.

发表于 2017-08-06 14:07:42 回复(0)

1Android中实现view的更新有两种方法,一种是invalidate,另一种是postInvalidateinvalidate是在UI线程自身中使用,而postInvalidate在非UI线程中使用。

2、当view确定自身已经不再适合现有的区域时,该view本身调用这个方法要求parent view(父类的视图)重新调用他的onMeasure onLayout来重新设置自己位置。特别是当viewlayoutparameter发生改变,并且它的值还没能应用到view上时,这时候适合调用requestLayout方法。

发表于 2017-02-15 17:45:15 回复(0)