android: onDraw is called constantly

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

I have a problem with a custom button. onDraw() gets called again and again, and I can't figure out why.

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

Button is used like that:

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

Any ideas what might be wrong?

回答1:

Change the drawableStateChanged() method:

  1. Don't call invalidate
  2. Call super.drawableStateChanged().


回答2:

Sorry, dumb failure:

this.getDefaultBitmap() had a setBackgroundColor(0x00000000); call in it which retriggered the onDraw.

So kind of a recursion:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!