ImageView显示网络图片
Posted newcaoguo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ImageView显示网络图片相关的知识,希望对你有一定的参考价值。
package com.example.urlimage; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; 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.Button; import android.widget.ImageView; public class MainActivity extends Activity { //声明地址 private Button btn; private ImageView img; private String url = "http://imgstore04.cdn.sogou.com/app/a/100520024/877e990117d6a7ebc68f46c5e76fc47a"; //在消息队列中实现对控件的更改 private Handler handle = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 0: System.out.println("111"); Bitmap bmp=(Bitmap)msg.obj; img.setImageBitmap(bmp); break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn); img = (ImageView) findViewById(R.id.img); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //新建线程加载图片信息,发送到消息队列中 new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Bitmap bmp = getURLimage(url); Message msg = new Message(); msg.what = 0; msg.obj = bmp; System.out.println("000"); handle.sendMessage(msg); } }).start(); } }); } //加载图片 public Bitmap getURLimage(String url) { Bitmap bmp = null; try { URL myurl = new URL(url); // 获得连接 HttpURLConnection conn = (HttpURLConnection) myurl.openConnection(); conn.setConnectTimeout(6000);//设置超时 conn.setDoInput(true); conn.setUseCaches(false);//不缓存 conn.connect(); InputStream is = conn.getInputStream();//获得图片的数据流 bmp = BitmapFactory.decodeStream(is); is.close(); } catch (Exception e) { e.printStackTrace(); } return bmp; } }
以上是关于ImageView显示网络图片的主要内容,如果未能解决你的问题,请参考以下文章
转载一行代码加载网络图片到ImageView——Android Picasso
我用的是xcode4.2,弄了一个imageview,现在我想让这个imageview显示网络上的图片,请问我该怎么做?