【问题标题】:CalledFromWrongThreadException when trying to start animation from thread [duplicate]尝试从线程启动动画时调用 CalledFromWrongThreadException [重复]
【发布时间】:2012-05-20 09:14:51
【问题描述】:

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

删除函数创建一个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();
}

我的足迹从这里开始:

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;
    } 
}

知道我该如何解决它吗? 谢谢

【问题讨论】:

  • @Andrew Thompson - 我会从你的帖子中尝试解决方案
  • (轻笑)在搜索“仅原始线程”时出现的 Google 上的热门话题(结果是在 SO,并且有一个公认的答案)并不是“我的线程”创建视图层次结构的可以触及其视图”。 ;)

标签: java android multithreading


【解决方案1】:

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

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

使用 runOnUiThreadHandler 从线程更新 UI

【讨论】:

  • 我会尝试像 Andrew Thompson 所说的 runOnUiThread 解决方案
  • 如果你有任何问题,很容易将你的线程转换为 runonuithread,然后评论我
猜你喜欢
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
  • 2012-08-02
  • 1970-01-01
相关资源
最近更新 更多