4

Here is my code:

    if (myView == null) {
        myView = new View(mContext) {
            @Override
            protected void onDraw(final Canvas canvas) {
                super.onDraw(canvas);
                final float width = (float)getWidth();
                ......
            }
        };

        addView(myView);
    }

    requestLayout();

The width in my code is always 0 although the size of the mContext is not zero. Can anybody advise what could be the possible reason I got 0 for width? Thanks

Bagusflyer
  • 12,675
  • 21
  • 96
  • 179

2 Answers2

3

You have to record the dimensions of the canvas in the onSizeChanged handler and then use them in the onDraw handler.

private int canvasWidth;
private int canvasHeight;

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    canvasWidth = w;
    canvasHeight = h;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    final float width = (float)canvasWidth;
    ...
}
Rob Meeuwisse
  • 2,847
  • 1
  • 17
  • 21
-1

Being a rookie I think your new view is blank thats y its width and height is coming 0. May b u should try to set its layoutparameter giving some hardcode height and width.

Currently onmeasure has nothing to measure. May B . :P