在Recyclerview中不使用第三方库加载多个Url图像 [英] Load multiple Url images without using third party libraries in Recyclerview
问题描述
大家好我刚接触Android,我很难通过URL将多个图像加载到Recycler视图中,我的任务不是使用任何第三方库,也不是在xml文件中添加字符串数组。是否可以循环URL?例如 http://onethousandpaintings.com/imgs/numbers/number_1.png ,如果数字改变,图像相应地改变。自己一次!我正在考虑在For Loop中增加该数字的方法,但无法弄明白。请给我一个解决方案。
Hi all I'm new to Android, I'm facing difficulty in loading Multiple images through URL into a Recycler view, My task is not to use any third Party Libraries and also not to add in string array in xml file. Is it Possible to loop an URL? for example "http://onethousandpaintings.com/imgs/numbers/number_1.png", if the number is change the image correspondingly changes.try it yourself once! I'm thinking an way to increment that number in a "For Loop" but could not figure it out. Kindly provide me an solution for it.
推荐答案
@sample AsycTask Code,你可以通过execute方法将url传递给这个类。
@sample AsycTask Code, you can pass the url to this class by execute method.
public class ShowImage extends AsyncTask<String,Void,Bitmap>{
private WeakReference<ImageView> imageview;
public ShowImage(ImageView imv){
imageview=new WeakReference<ImageView>(imv);
}
/** Background process
* input:url
* output: Bitmap image
* It passed into onPostExecute method
**/
@Override
protected Bitmap doInBackground(String... urls) {
return getBitMapFromUrl(urls[0]);
}
/** This method called after the doINputBackground method
* input:Bitmap image
* output: image set into the image view
* Image view passed from RecyclerViewOperation to ShowImage class through constructor
**/
@Override
protected void onPostExecute(Bitmap result) {
if((imageview!=null)&&(result!=null)){
ImageView imgview=imageview.get();
if(imgview!=null){
imgview.setImageBitmap(result);
}
}
}
/** This method called by doInBackground method
* input:url
* output: Bitmap image
*
**/
private Bitmap getBitMapFromUrl( String imageuri){
HttpURLConnection connection=null;
try {
URL url=new URL(imageuri);
// Log.d("bucky","bitmap" + imageuri);
connection= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap mybitmap=BitmapFactory.decodeStream(is);
return mybitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
finally {
if(connection!=null) {
connection.disconnect();
}
}
}
}
这篇关于在Recyclerview中不使用第三方库加载多个Url图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!