0

I want to remove an object from a list and in the same time i want to animate to the user a fade out animation...

The remove function create a Thread, in the thread i try to start the animation, but I'm getting that excetion:

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

On the activity:

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

When user will press the remove icon he will gets here:

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

My Tread start here:

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

Any idea how can i slove it? Thanks

choop
  • 921
  • 2
  • 9
  • 28
  • 1
    @Andrew Thompson - I'll try the solution from your thread – choop May 11 '12 at 19:04
  • 1
    (chuckles) it is not so much 'my thread' the top hit on Google (that turns out to be at SO, and has an accepted answer) that comes up when searching "Only the original thread that created a view hierarchy can touch its views". ;) – Andrew Thompson May 11 '12 at 19:10

1 Answers1

2

here TableRow tr = (TableRow) findViewById(R.id.test);

your are trying to access UI element from another thread.

use runOnUiThread or Handler for updating UI from thread

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213