【发布时间】:2023-03-30 04:20:01
【问题描述】:
我使用 this 显示来自 Internet 的图像,但它会引发如下错误:
04-12 13:45:05.337: E/AndroidRuntime(27897): Caused by: android .view.ViewRootImpl$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程才能接触其视图。
public class Order extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new DownloadFilesTask().execute();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(Void result) {
}
@Override
protected Void doInBackground(Void... params) {
setContentView(R.layout.order);
ImageView imageView = (ImageView)findViewById(R.id.imgView);
imageView.setImageDrawable(createDrawableFromURL("http://savagelook.com/misc/sl_drop2.png"));
return null;
}
}
private Drawable createDrawableFromURL(String urlString) {
Drawable image = null;
try {
URL url = new URL(urlString);
InputStream is = (InputStream)url.getContent();
image = Drawable.createFromStream(is, "src");
} catch (MalformedURLException e) {
image = null;
} catch (IOException e) {
image = null;
}
return image;
}
}
【问题讨论】:
-
参见“线程处理程序”techotopia.com/index.php/…
-
在 Mono 中,使用 RunOnUiThread... RunOnUiThread(() => { _tvMessage.Text = "Loading..."; }); mono-for-android.1047100.n5.nabble.com/…