//这是图片地址
String imageUrl = "http://139.224.43.42/medical/Uploads/head/07c3b4de0173f0128d6c2ec78c8e3828.jpg";
1、修改你的main.xml文件如下:<?xml version="1.0" encoding="utf-8"?>
<LineatLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Imageview
android:id="@+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
/>
</LineaLayout>
Step2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView imView = (ImageView) findViewById(R.id.imview);
imView.setImageBitmap(returnBitMap(imageUrl));
}
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
3、其中,returnBitMap(String url) 方法就是具体实现网络图片转换成bitmap。
4 ,如果你直接这样设置在有的手机上会报一个错误;
Caused by: android.os.NetworkOnMainThreadException;
解决方案详细请参考:http://www.jianshu.com/writer#/notebooks/5804231/notes/7123422
网友评论