<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textAllCaps="false"/>
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

package success.xiaoyu.loadimage;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Drawable drawable = (Drawable)msg.obj;
            imageView.setImageDrawable(drawable);

        }
    };
    private ImageView imageView;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        Button button = (Button)findViewById(R.id.button);
       imageView = (ImageView)findViewById(R.id.image);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Drawable drawable = loadImage("http://115.159.217.226/xy.jpg");
                        Message msg = new Message();
                        msg.obj = drawable;
                        handler.sendMessage(msg);
                    }
                }).start();
            }
        });
    }
    private Drawable loadImage(String path){
        Drawable drawable = null;
        try{
            drawable = Drawable.createFromStream(new URL(path).openStream(),"image.jpg");
        }catch (IOException e){
            e.printStackTrace();
        }
        return  drawable;
    }


}


版权声明:本文为hxy19971101原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/hxy19971101/article/details/76436718