1
我想運行一個經典的洪水填充算法,它具有算法進展的可視化表示;即一系列變黑的按鈕,以顯示算法的順序。我不想通過生成迭代版本的遞歸算法來作弊。 P提前 oorly標籤僞代碼:Android從遞歸算法更新ui
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)。
因此我實現可運行在algoithm(即
handler.post(可運行)的PAUSE線;
其中可運行是
private Runnable runnable = new Runnable() {
public void run() {
Log.d("RUNableworking","RUNableworking");
handler.postDelayed(this, 1000);
}
};
從此時,floodFill螺紋=沒有運行運行從onCreate我看到日誌很好。
我不太熱衷於輪詢可運行;必須有更好的方式做到這一點?
TBH,線程是複雜的事情。但只是使用vanilla函數(如上)似乎並沒有更新UI直到執行結束;雖然它沒有明確創建一個新線程,但我認爲它確實會產生問題? – stevenpcurtis
不,不使用onDraw();只需設置背景顏色switchbutt.setBackgroundColor(Color.BLACK); – stevenpcurtis
哦!我誤讀了。我以爲你使用的是像素繪圖,而不是按鈕。有時你必須使按鈕無效才能讓它們更新。我敢打賭,Android正在排隊BG變更請求,並一次性完成它們,而不是一個接一個。爲了達到這個目的,你肯定希望爲每次傳遞做一些計時器機制,或者迭代腳本按鈕 –