简体   繁体   English

从Thread设置imageView

[英]Set imageView from Thread

I am using a freind to download a picture and set in the ImageView ; 我正在使用freind下载图片并在ImageView设置; however, I get this error: 但是,我收到此错误:

Only the original thread that created a view hierarchy can touch its views. 只有创建视图层次结构的原始线程才能触及其视图。

This is my code. 这是我的代码。

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

The image_profile Bitmap is a valid Bitmap file. image_profile Bitmap是一个有效的Bitmap文件。 (I checked it via debug.) (我通过调试检查过。)

This thread is running in the OnCreate method. 该线程在OnCreate方法中运行。

You cannot update your UI directly from the Thread . 您无法直接从Thread更新UI。 Instead, use runOnUiThread() or equivalent. 而是使用runOnUiThread()或等效的。

Replace this : 替换这个

profilePic.setImageBitmap(image_profile);

With this : 有了这个

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

You cannot update ui on another thread. 你不能在另一个线程上更新ui。 Update ui on the main ui thread as below 在主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();

The problem isn't about the Bitmap . 问题不在于Bitmap The problem is that you are trying to do UI stuff in a separate Thread . 问题是你试图在一个单独的ThreadUI东西。 With the code you've given, there is no reason for the Thread . 使用您提供的代码,没有理由使用Thread Remove the Thread . 删除Thread If you are doing other things that you aren't showing then you can use runOnUiThread or an AsyncTask and update the ImageView in any method other than doInBackground() as it doesn't run on the UI 如果您正在执行其他未显示的内容,则可以使用runOnUiThreadAsyncTask并使用除doInBackground()之外的任何方法更新ImageView ,因为它不在UI运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM