尝试从线程启动动画时出现CalledFromWrongThreadException

时间:2012-05-11 18:51:31

标签: java android multithreading

我想从列表中删除一个对象,同时我想为用户设置一个淡出动画...

remove函数创建一个Thread,在线程中我尝试启动动画,但我得到了这个例外:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that      created a view hierarchy can touch its views.

关于活动:

private Animation animation;
private AnimationListener al;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    animation = AnimationUtils.loadAnimation(this, R.anim.fade_out);                
    al = new AnimationListener() {

        public void onAnimationStart(Animation animation) {
        // do nothing       
        }

        public void onAnimationRepeat(Animation animation) {
        // do nothing       
        }

        public void onAnimationEnd(Animation animation) {
            TableRow tr = (TableRow) findViewById(R.id.test);                   
            tr.setVisibility(View.GONE);
        }

    };

    animation.setAnimationListener(al);                             
    animation.reset();            
}

当用户按下删除图标时,他将到达此处:

public void remove(View v) {         
    RemoveF rf = new RemoveF();
    rf.start();
}

我的Tread从这里开始:

class RemoveF extends Thread {
    private boolean running;

    public void run() {
        running = true;
        try {
            do {
                //business logic goes here
                TableRow tr = (TableRow) findViewById(R.id.test);
                tr.setAnimation(animation);
                tr.startAnimation(animation);
                stopRunning();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    // do nothing
                }
            } while (running);
        } catch (Exception e) {
            Log.e("RemoveF", "Exception", e);
        }
    }

    public void stopRunning() {
        running = false;
    } 
}

我知道如何解决它? 感谢

1 个答案:

答案 0 :(得分:2)

此处TableRow tr = (TableRow) findViewById(R.id.test);

您正试图从另一个线程访问UI元素。

使用runOnUiThreadHandler从线程

更新UI