我试图让 GUI 在每次循环迭代后更新。我已经阅读了类似问题的其他答案,但仍然无法使其发挥作用。在下面的代码中,我调用模拟,它通过循环调用步骤运行,根据需要计算和更改 GUI 组件,但 GUI 直到循环完全结束后才会更新。如何让它在每次迭代后更新?
public void step(View v) {
for (int i = 0; i < cells.length; i++)
update(i);
count++;
Toast.makeText(getApplicationContext(), count + "", 1000).show();
}
public void simulate(View v) {
while (!pause) {
step(v);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void update(final int i)
{
//This goes through each button and counts the neighbors (this is the
//intensive work
int neighbors = getNeighbors(i);
//With the information provided from the getNeighbors the following if
//statement updates the GUI using the dead and alive method calls.
if (isAlive(cells[i])) {
if (neighbors < 2)
dead(cells[i]);
else if (neighbors > 3)
dead(cells[i]);
}
else {
if (neighbors == 3)
alive(cells[i]);
}
}
最佳答案
问题是您正在应用程序的主线程中运行该代码。 GUI 在同一线程上运行,并且在您阻止它时无法更新。
您必须在不同的任务中进行计算,然后向主进程发送消息以更新 GUI。 阅读本文以获取背景信息(如果您对此不熟悉,请先阅读背景信息):
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
最简单的方法是使用 AsyncTask,然后使用“onProgressUpdate()”进行 GUI 更新。 尽管 AsyncTask 已经使事情变得非常简单,但您必须注意,当 AsyncTask 运行时,底层 Activity 可能会被销毁。文档中并没有很好地介绍这一点,但我发现使用 fragment 可能是处理它的最佳方法。阅读这篇文章以获得非常好的描述:
http://blogactivity.wordpress.com/2011/09/01/proper-use-of-asynctask/
备注:另请阅读 AsyncTask 文档。由于论坛限制,我无法发布链接。
关于java - 如何在程序运行时更新GUI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11141957/