即使layout_height设置为wrap_content,自定义视图对象也会占用屏幕的全部高度
我创建了一个扩展了android.view.View
的对象,并覆盖了draw()
并将其显示在屏幕上.为了让您印象深刻,它是代表游戏得分的数字显示.它可以水平正确显示,但是占据了整个屏幕的高度-将所有其他元素推离了屏幕.
I created an object that extends android.view.View
, overriding draw()
and have it displaying on the screen. To put you in the picture, it is a display of digits to represent a game score. It's displaying correctly horizontally, however, it is taking up the full height of the screen - pushing all other elements off the screen.
我已经将layout_height="wrap_content"
放在xml中,但是没有效果.
I've put layout_height="wrap_content"
in the xml, but it has no effect.
有人知道我在做什么错吗?
Does anyone know what I am doing wrong?
我知道了...
我应该重写onDraw(),但这不是导致问题的原因.
I was supposed to override onDraw() but that wasn't what caused the problem.
最主要的是,我需要像这样重写onMeasure():
The main thing was, I needed to override onMeasure() like this:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(DIGIT_WIDTH * getNumberOfDigits(), DIGIT_HEIGHT);
}
DIGIT_WIDTH
和DIGIT_HEIGHT
是设置为我使用的每个数字图像的尺寸的常数. getNumberOfDigits()
只是从xml属性设置的自定义属性的获取器.
DIGIT_WIDTH
and DIGIT_HEIGHT
are constants set to the dimensions of each digit image I used. getNumberOfDigits()
is just a getter for a custom property set from the xml attributes.
希望可以帮助其他任何人.
Hope that helps anyone else coming across this.