你可以試試這個:
public static Drawable foo(String stringPath) {
File mFile = new File(stringPath);
File[] mFiles = mFile.listFiles();
for (File aFile : mFiles) {
if (isImage(aFile)) {
return Drawable.createFromPath(aFile.getPath());
}
}
return mPlaceholder;
}
public static boolean isImage(File file) {
if (file == null || !file.exists()) {
return false;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
return options.outWidth != -1 && options.outHeight != -1;
}
或者你可以用另外一種方式:
public static Bitmap foo(String stringPath) {
File mFile = new File(stringPath);
File[] mFiles = mFile.listFiles();
for (File aFile : mFiles) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(aFile.getAbsolutePath(),bmOptions);
if(bmOptions.outWidth != -1 && bmOptions.outHeight != -1){
return bitmap;
}
}
return mPlaceholder;
}
public static void bar(View view, String stringPath) {
Bitmap bitmap = foo(stringPath);
BitmapDrawable drawable = new BitmapDrawable(view.getContext().getResources(), bitmap);
view.setBackground(drawable);
}
使用BitmapDrawable與BitmapFactory – njzk2