我使用以下代码获取目录列表
String ROOT_DIR = Environment.getExternalStorageDirectory().getPath();
ROOT_DIR传递为字符串
public static ArrayList<String> getDirectoryPaths(String directory) {
ArrayList<String> pathArray = new ArrayList<>();
File file = new File(directory);
File[] listfiles = file.listFiles();
if (listfiles != null) {
for (int i = 0; i < listfiles.length; i++) {
if (listfiles[i].isDirectory()) {
pathArray.add(listfiles[i].getAbsolutePath());
}
}
}
return pathArray;
}
`
它返回所有目录路径,但我想获取包含图像的目录的路径,就像它在图库中显示的那样(Camera,WhatsAppImages,hike,...);我想得到所有这些的路径。
有什么想法吗?
答案 0 :(得分:6)
试试这个:
创建一个Bucket Class
public class Bucket {
private String name;
private String firstImageContainedPath;
public Bucket(String name, String firstImageContainedPath) {
this.name = name;
this.firstImageContainedPath = firstImageContainedPath;
}
public String getName() {
return name;
}
public String getFirstImageContainedPath() {
return firstImageContainedPath;
}
}
然后,添加此方法,它将返回存在Images的所有存储桶。
public static List<Bucket> getImageBuckets(Context mContext){
List<Bucket> buckets = new ArrayList<>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String bucketPath = cursor.getString(cursor.getColumnIndex(projection[0]));
String fisrtImage = cursor.getString(cursor.getColumnIndex(projection[1]));
file = new File(fisrtImage);
if (file.exists() && !bucketSet.contains(bucketName)) {
buckets.add(new Bucket(bucketName, fisrtImage));
}
}
cursor.close();
}
return buckets;
}
最后,创建自定义微调器项并使用适配器填充微调器。
下一步是使用所选存储桶中的图像填充gridview。 此方法将根据bucketpath返回所有图像。
public List<String> getImagesByBucket(@NonNull String bucketPath){
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME+" =?";
String orderBy = MediaStore.Images.Media.DATE_ADDED+" DESC";
List<String> images = new ArrayList<>();
Cursor cursor = mContext.getContentResolver().query(uri, projection, selection,new String[]{bucketPath}, orderBy);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String path = cursor.getString(cursor.getColumnIndex(projection[0]));
file = new File(path);
if (file.exists() && !images.contains(path)) {
images.add(path);
}
}
cursor.close();
}
return images;
}
最后,创建适配器并填充gridview。
我希望,它可以帮到你。