自定义View-onMeasure()方法

来源:互联网 发布:特朗普 中美关系 知乎 编辑:程序博客网 时间:2024/05/17 07:18

在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);
生效。

0 0
原创粉丝点击