Android ImageView如何加载网络图片资源
package com.android.antking.imageview; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { //定义一个图片显示控件 private ImageView imageView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //图片资源 String url = "http://s16.sinaimg.cn/orignal/89429f6dhb99b4903ebcf&690"; //得到可用的图片 Bitmap bitmap = getHttpBitmap(url); imageView = (ImageView)this.findViewById(R.id.imageViewId); //显示 imageView.setImageBitmap(bitmap); } /** * 获取网落图片资源 * @param url * @return */ public static Bitmap getHttpBitmap(String url){ URL myFileURL; Bitmap bitmap=null; try{ myFileURL = new URL(url); //获得连接 HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection(); //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制 conn.setConnectTimeout(6000); //连接设置获得数据流 conn.setDoInput(true); //不使用缓存 conn.setUseCaches(false); //这句可有可无,没有影响 //conn.connect(); //得到数据流 InputStream is = conn.getInputStream(); //解析得到图片 bitmap = BitmapFactory.decodeStream(is); //关闭数据流 is.close(); }catch(Exception e){ e.printStackTrace(); } return bitmap; } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28