我试图做自定义组件。我扩展了View
上课并在 onDraw
中画图被覆盖的方法。为什么我需要覆盖 onMeasure
?如果我没有,一切看起来都是正确的。有人可以解释一下吗?我应该如何写我的onMeasure
方法?我看过几个教程,但每个教程都有点不同。有时他们会调用 super.onMeasure
最后,有时他们使用 setMeasuredDimension
并没有调用它。区别在哪里?
毕竟我想使用几个完全相同的组件。我将这些组件添加到我的 XML
文件,但我不知道它们应该有多大。我想稍后在自定义组件类中设置它的位置和大小(为什么我需要在 onMeasure
中设置大小,如果在 onDraw
中,当我绘制它时也可以正常工作)。我到底什么时候需要这样做?
onMeasure()
您是否有机会告诉 Android 您希望自定义 View 依赖于父级提供的布局约束有多大?这也是您的自定义 View 了解这些布局约束的机会(如果您希望在 match_parent
情况下与 wrap_content
情况下表现不同)。这些约束被打包到 MeasureSpec
传递给方法的值。以下是众数值的粗略相关性:
layout_width
或 layout_height
value 被设置为一个特定的值。你可能应该把你的 View 设为这个大小。这也可以在 match_parent
时触发。用于将大小精确设置为父 View (这取决于框架中的布局)。 layout_width
或 layout_height
值设置为 match_parent
或 wrap_content
其中需要最大尺寸(这取决于框架中的布局),并且父尺寸的尺寸是值。你不应该比这个尺寸大。 layout_width
或 layout_height
值设置为 wrap_content
没有限制。你可以是任何你想要的尺寸。一些布局还使用此回调来确定您想要的尺寸,然后再确定在第二次测量请求中实际再次传递给您的规范。 onMeasure()
存在的契约(Contract)是setMeasuredDimension()
必须 最后以您希望 View 的大小调用。此方法被所有框架实现调用,包括在 View
中找到的默认实现。 ,这就是为什么调用 super
是安全的相反,如果这适合您的用例。wrap_content
的自定义 View 在这两个方向上,您的 View 可能根本不显示,因为框架不知道它有多大!View
而不是另一个现有的小部件,提供一个实现可能是一个好主意,即使它像这样简单:@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int desiredWidth = 100;
int desiredHeight = 100;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
//Measure Width
if (widthMode == MeasureSpec.EXACTLY) {
//Must be this size
width = widthSize;
} else if (widthMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
width = Math.min(desiredWidth, widthSize);
} else {
//Be whatever you want
width = desiredWidth;
}
//Measure Height
if (heightMode == MeasureSpec.EXACTLY) {
//Must be this size
height = heightSize;
} else if (heightMode == MeasureSpec.AT_MOST) {
//Can't be bigger than...
height = Math.min(desiredHeight, heightSize);
} else {
//Be whatever you want
height = desiredHeight;
}
//MUST CALL THIS
setMeasuredDimension(width, height);
}
关于android - onMeasure 自定义 View 说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12266899/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |