如何使用定时器线程和看法 [英] How to use timer-threads and views
问题描述
我的问题是:
我写了一个小Android应用程序,它使用许多ImageViews。
其的图像具有在code键被改变。
到目前为止,它工作得很好,但我想补充这类算法显示出正确的答案(这是一个游戏)。
他们应该会出现一个又一个。
My problem is: I wrote a little android app, which uses many ImageViews. Their Images have to be changed in the code. So far it worked fine, but I wanted to add kind of algorithm showing the right answer (it's a game). They should appear one after another.
public void x (int current,final View v)
{
c = current;
if(attached[current])
{
apply_change(c);
}
if(current < 34)
{
if(attached[current+1])
{
new java.util.Timer().schedule(new java.util.TimerTask(){
public void run(){
x(c+1,v);
}},500);
}
else
{
x(c+1,v);
}
}
else
new java.util.Timer().schedule(new java.util.TimerTask(){
public void run(){
//NewGame_Click(v);
finished = true;
}},1);
}
从这些线程我无法改变我的ImageViews(CalledFromWrongThreadException)的图像。
于是,我就这样做的:
From these threads I can't change the images of my ImageViews (CalledFromWrongThreadException). So I tried to do so:
while(!finished)
{
akt();
}
在我的UI线程。
的问题是,我的AKT();功能(它改变了图像)上运行,但没有什么可以我调试,手机的屏幕上之前没有完成可以看到所有的定时器线程。
in my UI Thread. The problem is, that my akt(); function (it changes the images) runs, but nothing can be seen on the screen of my Debug-Phone before not all of the Timer-Threads are finished.
我在做什么错了?
推荐答案
使用的处理程序。定时任务在不同的线程中运行。所以你不能从它更新UI。您应该更新主UI线程UI。您可以使用一个处理器或runonuithread定时器德run方法里面来更新UI。但我会建议你使用一个处理程序
Use a handler. Timer task runs on a different thread. So you cannot update ui from it. You should update ui on the main UI Thread. You can either use a handler or runonuithread inside the timer tak run method to update ui. But i would suggest you to use a handler
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
@Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000); // instad of 1000 mention the delay in milliseconds
}
};
m_handlerTask.run();
或者使用
runOnUiThread(new Runnable(){
@Override
public void run(){
//update ui here
}
});
这篇关于如何使用定时器线程和看法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!