如何在一段时间后取消选择视图而不冻结活动
我需要一些关于我的代码的好建议。 这就是我想做的。
我有一个活动,其中有一些可供用户选择的视图。假设用户选择了一个视图,我想在 5 秒后自动取消选择该视图。 我通过线程来完成此操作。
当用户选择视图时,我
Deselector deselect = new Deselector(mp.getDuration(), clickedview);
deselect.start();
在活动中调用... ...。
取消选择器类:
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();
}
}
}
我的程序崩溃了,logkitty 说
12-11 14:29:37.457: ERROR/AndroidRuntime(3263): android.view.ViewRoot$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能触摸其视图。
怎样做才正确呢?
预先感谢
m.d.
i need some good advice for my code.
here is what i want to do.
i have an activity that has some views 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在小部件或处理程序(而不是后台线程)上使用
postDelayed()
来在您建议的延迟之后执行工作。Use
postDelayed()
on a widget or aHandler
, rather than a background thread, to do work after your proposed delay.我通过对我的 deselctor runnable 执行以下操作来使其工作,
现在要短一些:
i got it working by doing the following
with my deselctor runnable now a bit shorter: