2015-09-20 15 views
0

我是新開發的Android開發人員,我使用drawables。我現在試圖訪問外部文件夾(從SD卡)並將圖像加載到int數組中,以便我可以使用它們。然而,經過對S.O的一些研究後,我仍然找不到可以幫助我的東西。Android - 將外部文件夾中的圖像加載到數組中

從我可繪製文件夾現在我把圖像(*。JPG),我讓他們在一個數組如下:

int[] image = { R.drawable.location, R.drawable.diversity, R.drawable.classes, R.drawable.activities, R.drawable.sports, R.drawable.friends, 
        R.drawable.graduate}; 

如何從外部文件加載圖像到類似像陣列東西以上?這裏的問題是圖像名稱。當我從外部文件夾加載它們時(假設它只包含圖像),我將如何獲取圖像名稱?

任何幫助將不勝感激。

謝謝。

+1

剛剛獲得與文件DIR =新的文件(路徑)的文件夾的內容; String [] files = dir.list(); – matty357

+0

@ matty357但這裏的問題是它不是一個int數組,它使我們無法使用'setImageResource(image [index]);'' – nTuply

回答

0

下面的方法將返回所有圖片的路徑從你的設備,讓這些路徑,並用它們來顯示圖像

public ArrayList<String> getFilePaths() 
     { 


      Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
      String[] projection = {MediaStore.Images.ImageColumns.DATA}; 
      Cursor c = null; 
      SortedSet<String> dirList = new TreeSet<String>(); 
      ArrayList<String> resultIAV = new ArrayList<String>(); 

      String[] directories = null; 
      if (u != null) 
      { 
       c = managedQuery(u, projection, null, null, null); 
      } 

      if ((c != null) && (c.moveToFirst())) 
      { 
       do 
       { 
        String tempDir = c.getString(0); 
        tempDir = tempDir.substring(0, tempDir.lastIndexOf("/")); 
        try{ 
         dirList.add(tempDir); 
        } 
        catch(Exception e) 
        { 

        } 
       } 
       while (c.moveToNext()); 
       directories = new String[dirList.size()]; 
       dirList.toArray(directories); 

      } 

      for(int i=0;i<dirList.size();i++) 
      { 
       File imageDir = new File(directories[i]); 
       File[] imageList = imageDir.listFiles(); 
       if(imageList == null) 
        continue; 
       for (File imagePath : imageList) { 
        try { 

          if(imagePath.isDirectory()) 
          { 
           imageList = imagePath.listFiles(); 

          } 
          if (imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG") 
            || imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")          
            || imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG") 
            || imagePath.getName().contains(".gif") || imagePath.getName().contains(".GIF") 
            || imagePath.getName().contains(".bmp") || imagePath.getName().contains(".BMP")       
      ) 
          { 



           String path= imagePath.getAbsolutePath(); 
          resultIAV.add(path); 

          } 
         } 
       // } 
       catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
      } 

      return resultIAV; 


     } 
相關問題