mmlooloo
mmlooloo

Reputation: 18977

Custom-view button onDraw() method does not draw

If I extend a button and override the onDraw method to draw something for example a circle and in XML layout file use:

<view class = "com.example.button.MainActivity$MyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

the circle appears but if I use this

<Button class = "com.example.button.MainActivity$MyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

Instead, nothing except the default rectangular view for button appears. why? The custom button class implementation is in extending android button by using onDraw and the onDraw() method is:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    Paint paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setStrokeWidth(10);
    paint.setStyle(Style.FILL);
    int width = canvas.getWidth();
    int height = canvas.getHeight();
    canvas.drawCircle(width/2, height/2, height/3, paint);
} 

Upvotes: 0

Views: 1306

Answers (1)

matiash
matiash

Reputation: 55350

When you want to use an inner class in an xml layout, the syntax is always:

<view class = "com.example.button.MainActivity$MyButton"
    ...
/>

If you use <Button ... the class attribute is ignored, that's why it's inflating and drawing a standard Button widget.

If you want MyButton to be a Button, just have its class extend it. You don't need to change the xml at all.

Upvotes: 1

Related Questions