加载网络图片,需要用到Bitmap对象。
加载网络图片有时也需耗时较长时间,所以也应该异步加载。
新建一个外部的ImgLoadTask类(可以更快速加载、提高代码复用性)
1.首先,新建一个Activity,布置其xml代码:
一个ImageView加载图片的地方
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.test.project.netconnection.NetPicActivity3">
<Button
android:id="@+id/showBtn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"
android:text="加载网络图片"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/image"
/>
</LinearLayout>
2.布置java代码:
在按钮点击事件里面加载LoadImgTAsk
用execute方法传入网络图片地址
private Button button;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_net_pic3);
bindId();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoadImgTAsk loadImgTAsk=new LoadImgTAsk(imageView);
loadImgTAsk.execute("http://n1.itc.cn/img8/wb/recom/2016/08/17/147140092923156017.JPEG");
}
});
}
private void bindId() {
button=findViewById(R.id.showBtn);
imageView=findViewById(R.id.imageView);
}
3.异步任务类LoadImgTAsk 代码:
public class LoadImgTAsk extends AsyncTask<String,Integer,Bitmap>{
private ImageView imageView;
public LoadImgTAsk(ImageView imgview){
this.imageView=imgview;
}
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bt=null;
try {
URL url=new URL(strings[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
bt= BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bt;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}
效果图
