我有问题,应该作为计时器。我已根据Android中使用的“计时器”阅读了这篇文章: http://developer.android.com/resources/articles/timed-ui-updates.html
我的布局中有TextView和ImageView。我在这个ImageView中有AnimationDrawable。我已经覆盖了AnimationDrawable类,因为我想知道我的动画何时完成。但是,我想在动画结束时调用runnable - 正常工作。但是,如果我想每秒更新TextView,另一个runnable(在下面的代码中)只调用一次(我可以在所有动画中看到数字“1”)。
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);
}
});
}
答案 0 :(得分:0)
您无法从工作线程调用UI方法。相反,您需要将mUpdateTimeTask中的代码更改为
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);
}
};
android dev指南中的Worker Thread部分有更多示例。