开发者

Android: How to get image files from directory into view.setBackgroundDrawable()

I'm trying to make an app that can take images from a directory on the android phone and display them in a layout. I seem to be working my way towards a solution in a backwards manner. I know to use view.setBackgroundDrawable(Drawable.createFromPath(String pathName)); to display the image, but I don't know how to get the image's path from the directory.

I have a vague idea of what to do, but would appreciate clarification on this matter. I think the next step is to use:

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    File file[] = Environment.getExternalStorageDirectory().listFiles();
}

But how do I filter the files so that only image files get stored in my file[]? Such as .png or .jpg/.jpeg files? And开发者_StackOverflow中文版 after that, should I use files[].getPath or files[].getAbsolutePath? I would store the result in a String[].

What I am mainly asking for is verification that the above code should work. And also, how I might filter to store only image files such as .png, .jpg and .jpeg.

Thank you for your time.


You want to do something like this for filtering:

File[] file = folder.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String filename) {

                    return filename.contains(".png");
                }
            });

If you want the filepath of the image of lets say the file at file[0], you would do this:

file[0].getAbsolutePath();


You want to implement a FileFilter and pass it to listFiles. You can create one that filters out only image files as you specified.

EDIT: and you want to use getAbsolutePath() as the argument to createFromPath.


Here is code for only to get .Png ,.jpg files and containing floders

private File[] listValidFiles(File file) {
    return file.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File dir, String filename) {
            File file2 = new File(dir, filename);
            return (filename.contains(".png") || filename.contains(".jpg") || file2
                    .isDirectory())
                    && !file2.isHidden()
                    && !filename.startsWith(".");

        }
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜