大家好我刚接触Android,我很难通过URL将多个图像加载到Recycler视图中,我的任务不是使用任何第三方库,也不是在xml文件中添加字符串数组。是否可以循环URL?例如“http://onethousandpaintings.com/imgs/numbers/number_1.png”,如果数字改变,图像会相应改变。自己一次!我正在考虑在“For Loop”中增加该数字的方法,但无法弄明白。请为我提供解决方案。
答案 0 :(得分:2)
@sample AsycTask Code,您可以通过execute方法将url传递给此类。
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();
}
}
}
}
答案 1 :(得分:0)
您可以使用AsynTask,因此它将从Url加载多个图像,这提供了在Background中工作的功能。因此,您的主线程不会受到影响,并且图像会在后台继续下载。我希望这能回答你的问题。