android - 从Android中的线程下载图像

标签 android android-layout

下面是我尝试将图像下载到 Android 应用程序内的 Activity 中。我的应用程序在 img1.setImageDrawable(d); 行崩溃我在 RelativeLayout 中有一个 LinearLayout。无法弄清楚为什么会一直崩溃。我总共需要四张图片才能下载到 Activity 中,我是否已正确设置 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>

最佳答案

你会喜欢AsyncTask:

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

他们给出的例子正是你想要的:如何下载文件。

关于android - 从Android中的线程下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7181451/

相关文章:

Android:fitsSystemWindows 和换行干扰 bottomSheets

Android 使 Activity 布局看起来与可绘制的初始屏幕相同

android - 不同的android设备有不同的颜色

android - 两个 AdMob 添加 - 集成问题

android - 使用Android Studio 1.3预览版编译NDK项目时出现问题

android - 在 Wear 和 Android 应用之间共享类(class)的最佳做法是什么?

android - 只有 LinearLayout 才能指定一个固定大小的元素,其相邻元素使用剩余空间吗?

android - 仅在 ListView 顶部时刷新屏幕(Android Studio)

android - 如何在Android Kotlin的RecyclerView中为CheckBox添加isChecked和unChecked事件

android - 没有标题栏的 ActionBar