android:onDraw不断被调用

时间:2011-10-18 22:24:07

标签: android

我的自定义按钮有问题。 onDraw()被一次又一次地调用,我无法弄清楚原因。

public class CircleButton extends Button {

    static final int StateDefault = 0;
    static final int StateFocused = 1;
    static final int StatePressed = 2;

    @Override
    protected void onDraw(Canvas canvas) {
        Log.v("Button","onDraw()");
        switch (mState) {
        case StateDefault:

            canvas.drawBitmap(this.getDefaultBitmap(), 0, 0, null);
            break;
        case StateFocused:
            canvas.drawBitmap(this.getFocusedBitmap(), 0, 0, null);
            break;
        case StatePressed:
            /*this.setWidth(3*radius);
            this.setHeight(3*radius);*/

            canvas.drawBitmap(this.getFocusedBitmap(), 0, 0, null);

            break;
        }
        super.onDraw(canvas);

    }

    @Override
    protected void drawableStateChanged() {
        Log.v("Button","drawableStateChanged()");
        if (isPressed()) {
            mState = StatePressed;

        } else if (hasFocus()) {
            mState = StateFocused;

        } else {
            mState = StateDefault;
        }
        // force the redraw of the Image
        // onDraw will be called!
        invalidate();
    }
    ...
}

按钮使用如下:

RelativeLayout buttonLayout = (RelativeLayout) this.findViewById(R.id.top_layout);
CircleButton shootButton = new CircleButton(this);
RelativeLayout.LayoutParams relativeParams1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
relativeParams1.addRule(RelativeLayout.CENTER_VERTICAL);
relativeParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeParams1.setMargins(0, 0, -20, 0);
buttonLayout.addView(shootButton, relativeParams1);

任何想法可能出错?

2 个答案:

答案 0 :(得分:2)

更改drawableStateChanged()方法:

  1. 请勿致电invalidate
  2. 致电super.drawableStateChanged()

答案 1 :(得分:2)

抱歉,哑巴失败:

this.getDefaultBitmap()有一个setBackgroundColor(0x00000000); 打电话给它重新启动onDraw。

这样的递归:

onDraw() - > getDefaultBitmap() - > setBackgroundColor() - > onDraw