_trd1启动时发生异常。为什么它会给出一个例外。我有一个图像视图,我已经在其上设置了动画。和我一样_imageCard2他们都工作得很好......但是当我添加一个新线程时,它会在完成后给出异常。
public void AnimFunction() {
TranslateAnimation animation2 = new TranslateAnimation(0, -50, 0, 0);
animation2.setDuration(100); // duration in ms
animation2.setRepeatCount(1);
animation2.setRepeatMode(Animation.REVERSE);
animation2.setFillAfter(false);
_imageView.startAnimation(animation2);
_imageView.setImageResource(R.drawable.b1fv);
// Animation
TranslateAnimation animation = new TranslateAnimation(0, 150, 0, 0);
animation.setDuration(400); // duration in ms
animation.setRepeatCount(1);
animation.setRepeatMode(Animation.REVERSE);
animation.setFillAfter(false);
_imageCard2.startAnimation(animation);
Thread _trd1 = new Thread() {
public void run() {
try {
sleep(2000);
_imageCard2.setImageResource(R.drawable.sk);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
_trd1.start();
}
尝试:
Thread _trd1 = new Thread() {
public void run() {
try {
sleep(2000);
runOnUiThread(new Runnable() {
@Override
public void run() {
_imageCard2.setImageResource(R.drawable.sk);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
您正在尝试从与 UI 线程不同的线程修改 UI 组件。
请考虑将处理程序与线程一起使用。
您还可以在AsyncTask中进行后台处理,该任务具有更新UI的方法。
编辑:一些解释:
UI = 用户界面。
您的活动在主线程(即 UI 线程)中运行。
不允许修改 UI 组件(按钮、图像视图等),但 UI 线程除外。
创建 trd1 线程时,您尝试从中修改图像视图。这就是您收到错误的原因。
runOnUiThread()
是可用于在 UI 线程而不是新创建的线程上进行修改的方法之一。