有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在尝试从线程启动动画时调用了FromErrorThreadException

我想从列表中删除一个对象,同时我想给用户制作一个淡出动画

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

安卓.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();
}

我从这里开始:

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) 个答案

  1. # 1 楼答案

    这里TableRow tr = (TableRow) findViewById(R.id.test);

    您正在尝试从另一个线程访问UI元素

    使用runOnUiThreadHandler从线程更新UI