从Thread设置imageView
我正在使用freind下载图片并在ImageView
设置; 但是,我收到此错误:
只有创建视图层次结构的原始线程才能触及其视图。
这是我的代码。
ImageView profilePicture =.... Thread thread = new Thread() { @Override public void run() { profilePic.setImageBitmap(image_profile); } }; thread.start();
image_profile Bitmap
是一个有效的Bitmap
文件。 (我通过调试检查过。)
该线程在OnCreate
方法中运行。
你无法在另一个线程上更新ui。 在主ui线程上更新ui ,如下所示
Thread thread = new Thread() { @Override public void run() { runOnUiThread(new Runnable() //run on ui thread { public void run() { profilePic.setImageBitmap(image_profile); } }); } }; thread.start();
您无法直接从Thread
更新UI。 而是使用runOnUiThread()
或等效的。
替换这个 :
profilePic.setImageBitmap(image_profile);
有了这个 :
YourActivityName.this.runOnUiThread(new Runnable() { @Override public void run() { profilePic.setImageBitmap(image_profile); } });
问题不在于Bitmap
。 问题是你试图在一个单独的Thread
做UI
东西。 使用您提供的代码,没有理由使用Thread
。 删除Thread
。 如果您正在执行其他未显示的内容,则可以使用runOnUiThread
或AsyncTask
并使用除doInBackground()
之外的任何方法更新ImageView
,因为它不在UI
运行