我需要创建一个循环,用来更新textView,想法是创建某种进度指示器,增量加载百分比。
我实现之后,只能看见最后一次更新,已经显示100%了,不能看见增量过程:
runOnUiThread(new Runnable() {
public void run() {
final TextView progesss = (TextView)findViewById(R.id.progress);
for(int k=1 ; k<=100; k++)
{
progesss.setText(String.valueOf(k) + "%");
try {
Thread.sleep(15);
} catch(InterruptedException e) {
}
}
}
});
不知道应该怎么实现我想要的效果。请大家帮忙。谢谢
你的Runnable代码在Thread.sleep阻塞了UI线程。不要用sleeping, 重新编一下Runnable again。用下面的代码:
final Handler handler = new Handler();
handler.post( new Runnable(){
private int k = 0;
public void run() {
final TextView progess = (TextView)findViewById(R.id.progress);
progess.setText(String.valueOf(k) + "%");
k++;
if( k <= 100 )
{
// Here `this` refers to the anonymous `Runnable`
handler.postDelayed(this, 15);
}
}
});
这样UI线程在每次调用时都能运行。