1

I'm writing a CustomSwitch. It is extended from Switch. Under some circumstances in the onDraw() method, I want to draw the CustomSwitch as a Button.

I tried several approaches, but neither did work. I can't call ((Button)this).draw(canvas); in the onDraw() cause thats going to result in a stack overflow. I tried to clone the CustomSwitch or inflate it and cast it to Button, but nether of those two approaches did work, too.

Does any body have another idea how I can draw a CustomSwitch as Button?

Angelo.Hannes
  • 1,729
  • 1
  • 18
  • 46

1 Answers1

1

Ok, here is what I did.

private Button drawButton;
public CustomSwitch(Context context) {
    super(context);
    this.drawButton = new Button(context);
}
public CustomSwitch(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.drawButton = new Button(context, attrs);
}
public CustomSwitch(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.drawButton = new Button(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    this.drawButton.measure(widthMeasureSpec, heightMeasureSpec);
};
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    this.drawButton.layout(left, top, right, bottom);
};
@Override
protected void onDraw(android.graphics.Canvas canvas) {
    //...
    if(condition) {
        this.drawButton.draw(canvas);
    }
}
Angelo.Hannes
  • 1,729
  • 1
  • 18
  • 46