1

I've created the child of RelativeLayout. In its constructor I called:

    public CanvasHolder(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.canvas_holder, this);    
        this.draw(new Canvas());
    }

And then override method onDraw():

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        black.setARGB(255, 0, 0, 0);
        black.setAntiAlias(true);
        int halfWidth = this.getWidth() / 2;
        int height = this.getHeight();
        canvas.drawLine(0, 0, halfWidth, height, black);
    }

No line has been appeared on the view. Also, I tried not to call "this.draw()", but nothing happened.

I've discovered that halfWidth and height equals 0. Why?

P.S. even if I set width and height statically, nothing will change. If you don't mind, take a look on this sample application: why nothing is drawn? http://androidforums.com/attachment.php?attachmentid=21715&stc=1&d=1315232946

QuickNick
  • 1,921
  • 2
  • 15
  • 30
  • Perhaps in your layout you have height and width set to wrap_content? Try changing it to fill_parent or something else like that. – Joru Sep 05 '11 at 09:22
  • No, I set static values 160px and 220px. – QuickNick Sep 05 '11 at 10:03
  • It might be because you are calling new Canvas() - it isn't actually attached to the view. If you want to a view to draw on, take a look at SurfaceView examples. – Joru Sep 05 '11 at 13:46
  • Yes, I've tried SurfaceView, but it worked unsatisfactory for me: it overlays another views (for example, it hides an rotateable arrow) and I couldn't make him transparent. – QuickNick Sep 05 '11 at 13:58

2 Answers2

0

Did you overwrite the onMeasure? Here's mine - you may find that this gets called a few times whilst the view is loading, sometimes with 0 values:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);

    if (parentHeight > 0) {
        this.setMeasuredDimension(parentWidth, parentHeight);
        // ... other stuff ...
    }
}
Martyn
  • 16,432
  • 24
  • 71
  • 104
  • Sorry. Nothing changed. I've tried to call from activity canvasHolder.draw(new Canvas()) 10 seconds later, but nothing was drawn. – QuickNick Sep 05 '11 at 10:03
0

I've found non-trivial solution. I've inited the view by the constructor with 1 parameter. And then I inserted the custom view in the layout and called invalidate() when I needed it.

QuickNick
  • 1,921
  • 2
  • 15
  • 30