在Android中从线程下载图像

时间:2011-08-24 19:55:18

标签: android android-layout

以下是我尝试将图像下载到Android应用程序内的活动中。我的应用程序崩溃在img1.setImageDrawable(d)行;我在RelativeLayout中有一个LinearLayout ..无法弄清楚为什么这会一直崩溃..我需要总共四个图像下载到活动,我是否正确设置xml以获得四个图像或我需要个人ImageView的?任何建议/想法/提示都非常感谢。

        Thread t = new Thread(){
        @Override
        public void run(){
            int i = imgarr.length;
            int j = 0;
            while(j<i){
                try {
                    InputStream is = (InputStream) new URL(imgarr[j]).getContent();
                    Drawable d = Drawable.createFromStream(is,"pic");
                    img1.setImageResource(d);
                    j++;
                } catch (MalformedURLException e) {} 
                  catch (IOException e) {}
            }
        }//end run
    };
    t.start();


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_below="@id/adbody"
>
<ImageView android:id="@+id/image1" android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingTop="15dip"/>
</LinearLayout>

2 个答案:

答案 0 :(得分:3)

你会爱AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

他们提供的示例正是您想要的:如何下载文件。

答案 1 :(得分:1)

如果您检查Logcat,您将看到您正在尝试更改未创建它的线程内的视图。 你需要使用处理程序。 或者您可以使用具有3种方法的AsyncTask。 一个用于下载之前发生的事情(在您的情况下没有任何内容)

一个用于下载

下载(设置ImageView)后发生的事情

请注意,“下载”部分不会在UI线程上运行,因此您不能在那里更改图像视图。

请在此处阅读:http://developer.android.com/resources/articles/painless-threading.html

相关问题