What triggers a View's measure() to be called

心已入冬 提交于 2019-12-03 00:56:38

In order to trigger a measure pass for a custom View you must call the requestLayout() method. For example, if you are implementing a custom view that extends View and it will behave like a TextView, you could write a setText method like this:

/**
 * Sets the string value of the view.
 * @param text the string to write
 */
public void setText(String text) {
    this.text = text;

            //calculates the new text width
    textWidth = mTextPaint.measureText(text);

    //force re-calculating the layout dimension and the redraw of the view
    requestLayout();
    invalidate();
}

Well, If you are changing a View's content, it will eventually have to call invalidate(). For example, you have a TextView with a text called "Text 1". Now, you change the text of the same TextView to "Text 2". Here aslo, invalidate will be called.

So basically, when something changes on the view, more often than not, you would expect the invalidate method to be called, and a corresponding call to the measure().

Look at the source code for TextView, for example. http://www.google.com/codesearch#uX1GffpyOZk/core/java/android/widget/TextView.java&q=TextView%20package:android&type=cs

Count the number of invalidate calls. There are quite a few.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!