Android从递归算法更新ui

标签 android user-interface recursion runnable

我想运行一个经典的洪水填充算法,该算法具有算法进展的可视化表示;即一系列变黑的按钮以显示算法的顺序。我不想通过生成递归算法的迭代版本来作弊。 P 前面带有标签的伪代码:

public void floodFill(int x, int y, String targetColor,String replacementColor) {
            if *out of bounds* return
              else
               if button = target then return
                else
                 Switchbuttontoblack(button);
                 PAUSE;
         floodFill(x - 1, y, targetColor, replacementColor);
         floodFill(x + 1, y, targetColor, replacementColor);
         floodFill(x, y - 1, targetColor, replacementColor);
         floodFill(x, y + 1, targetColor, replacementColor);
}

但是,虽然算法执行了,但是按钮只是在算法结束时一次性改变颜色。

这可能是由于非 UI 线程,如 Android timer updating a textview (UI) .

因此我在算法的暂停行实现了一个可运行的(即
handler.post(可运行);

哪里可以运行

private Runnable runnable = new Runnable() {
       public void run() {

            Log.d("RUNableworking","RUNableworking");
            handler.postDelayed(this, 1000);

       }
    };

从 Floodfill 线程运行 = 无。从 onCreate 运行,我看到日志很好。

我不太热衷于轮询可运行的;一定有更好的方法吗?

最佳答案

Activity 中有一个名为 runOnUiThread() 的命令,非常方便。唯一的问题是运行的 UI 是排队的。您还可以使用 Handler 对象将 UI 更新调用发送到 UI 线程。

但是,如果你要一步一步来,你真的需要使用另一个线程吗?

更新:您是否在 onDraw() 中进行了洪水填充?如果是这样,就不会一步步走

关于Android从递归算法更新ui,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233444/

相关文章:

安卓硬件属性

Android WebView : Intercept redirect requests?

android - 使用 IFNULL 会阻止 SQLite 使用索引吗?

java - 如何在 JPanel 上用 Java 绘制彩色圆圈?

c++ - QT - 多选

algorithm - Haskell while循环哪里递归根本行不通?

android - 如何为每次测试运行重新创建数据库?

android - 在特定的 x\y 坐标上绘制自定义 View

python - 如何使用递归遍历多个列表

c - 这两种方式在递归上有什么区别呢?