我正在尝试创建一个连接到站点的小型服务来进行操作,并在此过程中更新当前的textview
。在进入for循环之前,没有任何问题,因为该活动停止了,直到它没有结束时它才变成白色。
我想逐步更新文本。
我创建了一个异步任务,但它给我错误'
failed to load window
。
下面是我的代码,我声明我放了所有权限。
public class GameTask extends AsyncTask<String, Integer, Long> {
private ProgressBar progressBar;
private TextView text;
public GameTask(ProgressBar progressBar, TextView text) {
this.progressBar = progressBar;
this.text = text;
}
@Override
protected Long doInBackground(String... strings) {
startGameThread(progressBar, text);
return null;
}
private void startGameThread (final ProgressBar progressBar, final TextView text) {
final Handler mHandler = new Handler();
final Runnable mRunnable = new Runnable() {
@Override
public void run() {
try {
progressBar.setProgress(0);
text.setText("Thread Iniziato...");
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
text.setText("NUMBER " + i);
}
}
progressBar.setProgress(100);
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(mRunnable).start();
}
}
答案 0 :(得分:2)
尝试将此方法导入AsyncTask
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
try {
progressBar.setProgress(0);
text.setText("Thread Iniziato...");
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
text.setText("NUMBER " + i);
}
}
progressBar.setProgress(100);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
由于此进程正在AsyncTask中运行,因此您需要使用runOnUiThread方法来更新TextView。用户界面只能在MainThread上更新。
private void startGameThread () {
// final Handler mHandler = new Handler();
final Runnable mRunnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
final int finalI = i;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(String.valueOf(finalI));
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(mRunnable).start();
}
答案 2 :(得分:0)
您可以充分利用AsyncTask
来在没有Handler
的情况下在后台和UI线程中执行任务:
public class GameTask extends AsyncTask<String, Integer, Long> {
private ProgressBar progressBar;
private TextView text;
public GameTask(ProgressBar progressBar, TextView text) {
this.progressBar = progressBar;
this.text = text;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// UI thread
text.setText("Thread Iniziato...");
}
@Override
protected Long doInBackground(String... strings) {
// Non-UI thread
for (int i = 0; i <= 1000; i++) {
if (i == 0 || i % 10 == 0) {
publishProgress(i/100, i);
} else {
publishProgress(i/100);
}
try {
Thread.sleep(100); // Backpressure if needed for your sample
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// UI thread
progressBar.setProgress(values[0]);
if (values.length > 1) {
text.setText("NUMBER " + values[1]);
}
}
}