开发者

which causes the custom button text update UI Thread (or) onDraw in Android

I subclassed a class to Button and overriden the onDraw() method. And have written a handler in the constuctor of the class where I am updating a variable whose value has to be updated to that button text. Below is the code snippet,

   public class CustomButton extends Button{



        CustomButton(){
                handler = new Handler();
                Runnable runObj = new Runnable(){
                  public void run(){
                      counter++;
                      handler.postDelayed(this,1000);                  
                  }
                };
               handler.post(runObj);
        }

    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);       
        setBackgroundResource(R.drawable.button9patch);     
        setTextColor(COMPONENTTEXTCOLOR);
        setText(counter);       
    }

   }

Well the button text gets updated. I know that the onDraw() method gets called when the button gets rendered initially and when we do some amendments to the button view like setting the label or image etc.,.

Here in my code I am updating the counter outside of the onDraw() method, but calling the setText(counter) explicitly from onDraw() method. As I am not calling setText(counter) from the Hanlder code How it is upda开发者_运维问答ting the button text periodically?

Is it that the UI thread that causes the counter variable changes updated to the button periodically?

I am confused.

Thanks


You are never starting the Handler for the first time.

handler.postDelayed(runObj,1000);           

Update:

Every time you update the counter you must force the button to redraw itself:

counter++;
CustomButton.this.postInvalidate();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜