2015-10-30 67 views
-1

大家好我是Android的新手,我很難通過URL將多個圖像加載到Recycler視圖中,我的任務是不使用任何第三方庫和也不要在xml文件中添加字符串數組。是否有可能循環一個URL?例如「http://onethousandpaintings.com/imgs/numbers/number_1.png」,如果該數字改變圖像相應改變,一次嘗試!我正在想辦法在「For循環」中增加該數字,但無法弄清楚。請爲我提供一個解決方案。在Recyclerview中加載多個Url圖像而不使用第三方庫

+0

第三方庫會在更大程度上減少您的工作,如果您想選擇總是受歡迎的困難方式。我認爲這是一個任務問題 –

+0

你知道任何解決方案嗎? –

+0

然後使用它在工作室的庫中構建的抽象圖像加載器 –

回答

0

您可以使用AsynTask,以便從Url加載多個圖像,該圖像提供了在後臺工作的功能。因此,您的主線程不會受到影響,並且圖像將不斷下載到後端。我希望這回答你的問題。

2

@sample AsycTask Code,你可以通過執行方法將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(); 
      } 
     } 
    } 

}