我正在尝试设置一个很长的字符串。它会阻止 UI 线程 2-3 秒。
在异步任务中只有doInBackground()
在后台,其他函数使用 ui 线程,我不能在后台线程或doInBackground()
中使用setText()
- textview 有没有更快的替代方案?
在 onPostExecute(( 中,您可以更新文本视图。
// This method runs on UI thread.
protected void onPostExecute(String result) {
addResultToTextView(result);
}
有关更多详细信息,请参阅 https://developer.android.com/reference/android/os/AsyncTask.html。
您需要将
工作结果设置为异步任务onPostExecute()
public class MyAsyncTask extends AsyncTask<Url, Integer, String> {
protected String doInBackground(URL... urls) {
// for example, download something
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return String.valueOf(totalSize);
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(String result) {
textView.setText(result);
}
}
另外,您可以在AsyncTask用法中找到此示例