Custom view object using up full height of screen even when layout_height is set to wrap_content

寵の児 提交于 2019-12-07 06:47:55

问题


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.

I've put layout_height="wrap_content" in the xml, but it has no effect.

Does anyone know what I am doing wrong?


回答1:


I've figured it out...

I was supposed to override onDraw() but that wasn't what caused the problem.

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 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.



来源:https://stackoverflow.com/questions/3422806/custom-view-object-using-up-full-height-of-screen-even-when-layout-height-is-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!