我正在尝试创建一个更新TextView的循环。 我们的想法是创建某种进度指标,这将增加 loading precentge。
这是我尝试过的,但结果是我只看到循环的最后一次更新,所以我得到“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) {
}
}
}
});
有关如何实现目标的任何想法? 谢谢!
答案 0 :(得分:2)
执行Runnable
时,Thread.sleep
阻止了 UI线程。您应该再次发布一个新的Runnable
,而不是睡觉。试试这样的事情:
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线程有机会在每次调用之间运行,让它像处理输入和绘制屏幕上的内容一样。
答案 1 :(得分:0)
您使用后台线程和UI线程。
public class testAsync extends AsyncTask<Void, Integer, Voi>{
TextView progress; // You will set TextView referans
protected void doInBackground(){
for(int k=1 ; k<=100; k++)
{
try {
Thread.sleep(1000);
publishProgress(k);
} catch(InterruptedException e) {}
}
}
protected void onProgressUpdate(Integer.. values)
{
progress.setText(values[0]+");
}
}
}