4. Loading pictures
In practical applications, it is often necessary to download and display pictures from the network. Volley also provides several ways to download pictures from the web, here are two main approaches: Imagerequest and Imageloader.
(1) Imagerequest
Imagerequest and Stringrequest, jsonobjectrequest similar, are inherited from the request, the use of the same method.
Private voidimagerequest () {imagerequest imagerequest=NewImagerequest ("Http://tech.cnr.cn/techit/201411/W020141113510671880058.jpg", NewResponse.listener<bitmap>() {@Override Public voidOnresponse (Bitmap response) {Imgview.setimagebitmap (response); } }, 0, 0, config.rgb_565,NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {Imgview.setimageresource (r.drawable.ic_launcher); } }); Mqueue.add (imagerequest); }
First create a imagerequest, the parameters of the constructor include the URL of the image, download the image of the successful callback function (here to download the picture through a ImageView control display), the image display of the length and width (here is set to 0, the image is displayed in the original size), Image display of the quality, download the image of the failed callback function (this shows a default picture). The results of the operation are as follows:
(2) Imageloader
Sometimes it takes a long time to download pictures from the Internet, it is better to show a picture in the process of downloading, imageloader can realize this function. Imageloader is not inherited from request, and the use of the previous request is slightly different, you need to define Imageloader and Imagelistener, and then call Imageloader's Get () method to get the picture.
Define Imageloader:
New New Imagecache () { @Override publicvoid putbitmap (String URL, Bitmap Bitmap) { } @Override public Bitmap getbitmap (String url) { returnnull ; } });
Where Mqueue is the request queue.
Define Imagelistener:
Imagelistener listener = Imageloader.getimagelistener (imgview, R.drawable.ic_launcher, R.drawable.ic_ Launcher);
Where Imgview is the control that displays the picture, and the next two parameters are the pictures displayed during the download of the picture and the picture that the download failed to display, here for the sake of simplicity, the same picture is set.
Finally, use the Get () method of Imageloader to download the picture.
Imageloader.get ("Http://tech.cnr.cn/techit/201411/W020141113510671880058.jpg", 400, 200);
The parameters include the URL of the picture, the Imagelistener, the length and width of the image display. The results of the operation are as follows:
Use of Android Volley framework (3)