CustomView's "onDraw()"-Method never gets called

100 Views Asked by At

Here's a tricky one:

I'm writing my custom ImageView:

public class CustomImageView extends View

The picture to display is set via setImagePath(String path) and the BitMap loaded inside from the assets folder. That's working pretty fine, image dimensions are verified.

In later progress, the CustomImageView-Object is added to a LinearLayout (matches parent) via addView(View v). The overridden method

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)

gets called and calculates some loony values, nothing important at this point.

The weird thing is that the bottom value always is zero! And I think thats the point why onDraw(Canvas c) never gets called.

E/CIView﹕ onLayout - changed: true, left: 0, top: 0, right: 1080, bottom: 0
E/CIView﹕ bitmap - bitmapWidth: 735, bitmapHeight: 490
E/CIView﹕ onLayout - changed: false, left: 0, top: 0, right: 1080, bottom: 0
E/CIView﹕ bitmap - bitmapWidth: 735, bitmapHeight: 490

Can anybody explain to me why onLayout never gets the right bottom-value? Methods like invalidate() or requestLayout() didn't change anything, maybe I missed some special part..?

1

There are 1 best solutions below

1
On BEST ANSWER

If you override View you need to provide its size - which is why you're getting zero height bounds. So implement onMeasure() and inside that call setMeasuredDimension().

E.g.

@Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
setMeasuredDimension(bitmapWidth, bitmapHeight); }

Though you should check that there is enough space using

MeasureSpec.getSize(widthMeasureSpec) and

MeasureSpec.getSize(heightMeasureSpec)