我需要从循环更新的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'噢。好吧,它运行得太快了。 –