下载后,ImageView不会更改图像

时间:2011-10-13 09:25:55

标签: java android multithreading imageview

我是开发Android应用程序的初学者。我正在尝试使用线程将图像从an URL加载到ImageView。我的想法是在不中断整个过程的情况下加载图像。

问题是ImageView在下载完图片后没有加载图片;我必须单击主页按钮才能ImageView加载图像。

我的代码中有错误吗?

public class imageActivity extends Activity {
    private ImageView imgView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imgView =(ImageView)findViewById(R.id.img);

        new Thread() {
            @Override
            public void run() {
                try {
                    Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
                    imgView.setImageDrawable(drawable);
                } catch (Exception e) {
                    Log.e("TAG","" + e);
                }
            }
        }.start();
    }

    private Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

因为您应该在UI线程中设置Drawable。喜欢这个

        new Thread() {
        @Override
        public void run() {
            try {
                final Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
                imgView.post(new Runnable(){
                    imgView.setImageDrawable(drawable);
                });
            } catch (Exception e) {
                Log.e("TAG","" + e);
            }
        }
    }.start();

答案 1 :(得分:0)

我使用Prime来加载所有图像,它会让这样的动作变得非常简单。