开发者

updating the UI from the handler in another Runnable

I have problem with something, which should work as a timer. I have read this article according to the using "timer" in Android: http://developer.android.com/resources/articles/timed-ui-updates.html

I have the TextView and ImageView in my layout. I have AnimationDrawable in this ImageView. I have overrided the AnimationDrawable class, because I want to know when my animation is completed. However, the runnable I want to call when my animation is ended - work properly. But in case, when I want to upadate TextView each second, anot开发者_高级运维her runnable (in the code below) is calling only once (I can see the number "1" during all the animation).

TextView timeFlow;
int seconds;

private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {            
           seconds++;             
           timeFlow.setText(String.valueOf(seconds));          
       }
};

private void startAnimation() {      
    image = (ImageView) this.findViewById(R.id.image);      
    recordImage.setBackgroundResource(R.drawable.record_animation);
    timeFlow = (TextView) this.findViewById(R.id.time_flow);
    timeFlow.setText("...");            

    image.post(new Runnable() { 
    @Override
    public void run() {
        CustomAnimationDrawable currentAnimation = new CustomAnimationDrawable((AnimationDrawable) recordImage.getBackground());
        currentAnimation.setOnFinishCallback(runnable);
        recordImage.setBackgroundDrawable(currentAnimation);
        currentAnimation.start();                               

        handler.removeCallbacks(mUpdateTimeTask);
        handler.postDelayed(mUpdateTimeTask, 100);                                          
        }
    });     
}


You cannot call a UI method from a worker thread. Instead you need to change the code in mUpdateTimeTask to

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {            
         seconds++;             
         timeFlow.post(new Runnable() {
               timeFlow.setText(String.valueOf(seconds));
         });
         // It's not clear if handler is accessible here, but you get the picture.
         handler.postDelayed(mUpdateTimeTask, 100); 
    }
};

The Worker Thread section in the android dev guide has more examples.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜