Android: drawing on the Canvas and View (without Bitmap)
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_IN开发者_开发问答FLATER_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
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 ...
}
}
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.
精彩评论