2012-10-16 38 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); 
    } 
}