我需要從循環更新的Android按鈕,使每個按鈕高亮逐一
如何在循環中更新循環中的Android UI元素?
我試圖使用的AsyncTask沒有成功,同樣與處理程序。
處理程序下面的例子[從代碼的一部分,只給你舉例]:
for(i=1;i<10;i++){
final int value = i;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
Button currentButton = (Button) findViewById(value);
currentButton.setPressed(true);
}
});
}
};
new Thread(runnable).start();
任何想法如何到達用戶界面元素逐一?
又如:例如在標準循環如下:
- 通過ID獲得按鈕
- setPressed(真),使按鈕高亮
- 執行想要的功能
- setPressed(假的),只有當先前的一步完成。
問題:在運行按鈕的循環沒有更新,只有當循環結束後,在此情況下,用戶不會明白什麼步驟執行:
下面的代碼是開始,所有環路的事件:
View.OnClickListener OnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
button.setText("text now set.. ");
UpdateStep updateStep;
for(int i=1; i<stepsArray.size();i++)
{
final int value = i;
Button currentButton = (Button) findViewById(i);
currentButton.setHighlightColor(0x7f050003);
currentButton.setPressed(true);
for(int x=0;x<900000;x++); // will be replaced with the real function
currentButton.setPressed(false);
}
}
};
您應該首先了解*爲什麼*您的應用程序在循環中時UI不會更新。接下來,您應該(如您第一次嘗試的那樣)學習如何異步運行代碼,即在單獨的線程上運行代碼。 –
@Ed - 這不是在UI線程上運行。注意發佈代碼的最後一行? –
@Ted:....... d'噢。好吧,它運行得太快了。 –