2012-10-16 50 views
1

我在写一个CustomSwitch。它从Switch延伸。在onDraw()方法的某些情况下,我想将CustomSwitch作为一个按钮来绘制。CusotomSwitch绘制为按钮

我尝试了几种方法,但都没有工作。我不能在onDraw()中调用((Button)this).draw(canvas);,因为这会导致堆栈溢出。 我试图克隆CustomSwitch或将它膨胀并将它投射到Button,但是这两种方法都没有效果。

是否有任何机构有另一个想法如何我可以绘制一个CustomSwitch作为按钮?

+0

CustomSwitch从视图扩展? – neworld

+0

CustomSwitch扩展自[Switch](http://developer.android.com/reference/android/widget/Switch.html) –

回答

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); 
    } 
}