How to deselect view after a certain time without freezing activity
i need some good advice for my code. here is what i want to do.
i have an activity that has some view开发者_开发技巧s that can be selected by user. assumed that the user selected a view, i want to deselect this view automatically after, let's say, 5 seconds. I do this by a thread.
when the user selects the view, i call...
Deselector deselect = new Deselector(mp.getDuration(), clickedview);
deselect.start();
...in the activity.
the deselector class:
class Deselector extends Thread
{
int millis=0;
View view = null;
Deselector(int millis, View view)
{
this.millis = millis;
this.view = view ;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
this.sleep(millis);
view.setSelected(false);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
my program crashes and logkitty says
12-11 14:29:37.457: ERROR/AndroidRuntime(3263): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
how to do it right?
thanks in advance
m.d.
Use postDelayed()
on a widget or a Handler
, rather than a background thread, to do work after your proposed delay.
i got it working by doing the following
clickedview.postDelayed(new Deselector(clickedview), mp.getDuration());
with my deselctor runnable now a bit shorter:
class Deselector implements Runnable
{
View view = null;
Deselector(View view)
{
this.view = view ;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
view.setSelected(false);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
精彩评论