栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ImageView展示网络图片

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ImageView展示网络图片



    

java

package com.commerce.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    MyHandler myHandler;
    protected static final int CHANGE_UI = 1;
    ImageView imageView;

    class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == CHANGE_UI) {
                Bitmap bitmap = (Bitmap) msg.obj;
                imageView.setImageBitmap(bitmap);
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.myimagetive);
        myHandler = new MyHandler();
    }

    public void getmypic(View view) {

        imageView.setBackground(getResources().getDrawable(R.drawable.ic_launcher_background));
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url = new URL("https://p3.ssl.qhimgs1.com/t01d2446155618ebfc9.jpg");
                    HttpURLConnection httpURLConnection;
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(500);
                    httpURLConnection.setRequestMethod("GET");
                    int code = httpURLConnection.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        Message message = new Message();
                        message.what = 1;
                        message.obj = bitmap;
                        myHandler.sendMessage(message);


                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }.start();


    }
}

绿色的android

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/978722.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号