2014-02-15 597 views
1

我需要从用户的照片库中随机选择一张图片。我的意思不是开始的意图在如何从照片库中随机选择一张图片

Intent gallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
     startActivityForResult(gallery, GALLERY_PHOTO_REQUEST_CODE); 

号我需要随机选择图像我自己。有没有一种有效的方法来做到这一点?或者我必须真正阅读所有的图像文件,然后随机选择一个文件,然后从文件中获取图像?通过阅读所有的文件,我的意思的东西为(段:我有一个问题没有回答)

void addFiles(final File parent, Set<File> images) { 
     try { 
      for (final File file : parent.listFiles()) { 
       if (!file.getParent().contains("Android")) { 

        if (!file.isDirectory()) { 
         if (isImageFile(file.getName())) { 
          images.add(file); 
         } 
        } else { 
         addFiles(file, images); 
        } 
       } 
      } 
     } catch (Exception e) { 
     } 
    } 

请不要太在意的代码片段。如果我知道最好的方法,我不会寻求帮助。有谁知道这样做的有效方式?

回答

0

我不知道你的代码,除了片段。除非你有大量的文件,否则你可以很好地将所有文件读入数组。然后生成一个随机数,其中0表示最低值,arrayList.size() - 1表示最高值,并从数组中获得该索引。

伪代码:

private static Random random = new Random(); 

ArrayList<File> list = readFiles(); 
File randomFile = list.get(getRandomValue(0, list.size()-1)); 
... 

public static int getRandomValue(int low, int high) { 

    return random.nextInt((high - low) + 1) + low; 

} 
相关问题