我有一个自定义视图(android),它绘制一个自定义进度条。我希望进度条填充其父视图(宽度)。我遇到的问题是我不知道自定义视图如何获得其真正的限制。它需要知道宽度限制才能以正确的比例显示不同的颜色。我通过以下方式实现了 onMeasure():
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
setMeasuredDimension(widthMeasureSpec, 15);
}
然后,在 onDraw() 中,当我调用 getWidth()
时,我得到:1073742246。我怎样才能知道真正的父边界?显然我在这里做错了...视图布局参数设置为 MATCH_PARENT/FILL_PARENT 并且我可以在整个区域上绘制,但我不知道实际宽度以便以正确的比例绘制条形。
谢谢,
诺姆
I have a custom view (android) which draws a custom progress bar. I want the progress bar to fill its parent view (width). The problem that I have is that I don't know how the custom view can get its real limits. it needs to know the width limits in order to display different colors in the right ratio. I've implemented onMeasure() in the following way:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
setMeasuredDimension(widthMeasureSpec, 15);
}
Then, in my onDraw(), when I call getWidth()
I get: 1073742246. How can I know the real parent bounds? obviously I did something wrong here... the view layout params are set to MATCH_PARENT/FILL_PARENT and I can draw on the entire area but I don’t know the real width in order to draw the bars in the right proportion.
Thanks,
Noam
发布评论
评论(2)
widthMeasureSpec 包含除像素宽度之外的其他信息。看起来 onMeasure 正在尝试使用
MeasureSpec.EXACTLY
模式向您传递 422px 作为宽度。使用MeasureSpec.getSize(widthMeasureSpec);获取实际宽度(以像素为单位)。有关更多详细信息,请参阅 http://developer.android.com/reference /android/view/View.MeasureSpec.html
widthMeasureSpec includes other information than just the width in pixels. It looks like onMeasure is trying to pass you 422px as width with the mode
MeasureSpec.EXACTLY
.Use
MeasureSpec.getSize(widthMeasureSpec)
; to get the actual width in pixels. For more details, please see http://developer.android.com/reference/android/view/View.MeasureSpec.html该值包含所需的宽度,但它还包含 MeasureSpec 标志。
使用 MeasureSpec.getSize() 来剥去旗帜。
This value contains the needed width, but it also contains MeasureSpec flags.
Use MeasureSpec.getSize() to strip the flags.