1

我正在写一个CustomSwitch。它是从Switch扩展而来的。在onDraw()方法中的某些情况下,我想将CustomSwitch 绘制为Button。

我尝试了几种方法,但都没有奏效。我无法调用((Button)this).draw(canvas);onDraw()导致堆栈溢出的原因。我试图克隆 CustomSwitch 或对其进行充气并将其转换为 Button,但这两种方法都没有奏效。

有没有人知道如何将 CustomSwitch 绘制为 Button?

4

1 回答 1

1

好的,这就是我所做的。

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);
    }
}
于 2012-10-16T09:12:08.653 回答