2013-04-13 45 views
2

我正在使用一个朋友下载图片并设置在ImageView;然而,我得到这个错误:设置imageView线程

Only the original thread that created a view hierarchy can touch its views.

这是我的代码。

ImageView profilePicture =.... 
Thread thread = new Thread() { 
    @Override 
    public void run() { 
     profilePic.setImageBitmap(image_profile); 
    } 
}; 
thread.start(); 

的image_profile Bitmap是一个有效的Bitmap文件。 (我通过调试进行了检查。)

此线程运行在OnCreate方法中。

回答

3

您无法在另一个线程上更新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(); 
4

不能从Thread直接更新UI。相反,请使用runOnUiThread()或同等产品。

替换此

profilePic.setImageBitmap(image_profile); 

有了这个

YourActivityName.this.runOnUiThread(new Runnable() { 
    @Override 
    public void run() { 
     profilePic.setImageBitmap(image_profile); 
    } 
}); 
1

的问题不是关于Bitmap。问题是,你正试图在单独的Thread中做UI的东西。使用您提供的代码,Thread没有任何理由。删除Thread。如果你正在做的,你是不是再出其他的东西,你可以使用runOnUiThreadAsyncTask和更新,因为它不会对UI

+0

+1解释运行其他任何方法比doInBackground()ImageView,而不是放弃代码 – Pragnani

+0

@Pragnani谢谢!这意味着你很多 – codeMagic