自定義View-onMeasure()方法

在android自定義View的時候經常需要複寫View的onMeasure()方法,但是有些時候卻並不需要。瞭解其中的原因有助於我們深刻掌握自定義view。
首先看一下View中onMeasure()方法的官方解釋:

Measure the view and its content to determine the measured width and the measured height. This method is invoked by {@link #measure(int, int)} and should be overridden by subclasses to provide accurate and efficient measurement of their contents.

大概意思就是該方法會測量View,從而決定View的大小,需要我們複寫它。光這幾句話很難明白其真正的用法。
當沒有複寫onMeasuer()方法時,我們使用march_parent和wrap_content效果一樣,都是填充父控件。所以當我們自定義的View想自己定義大小,而又使用wrap_content時就需要複寫onMeasure()。在複寫的onMeasure()里根據你的需求重新的定義View的大小,然後通過:
setMeasuredDimension(measuredWidth, measuredHeight);
生效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章