我试图从外部SD card
内的特定文件夹中获取图片,并尝试在运行应用时将其显示在列表中。没有提供错误,没有任何反应。只是一个空白页面的任何建议。
我正在获取带扩展名的图像列表,但我如何查看图像!
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File file = new File("/sdcard/external_sd/folder_name/");
File imageList[] = file.listFiles();
ArrayList<Bitmap> images = new ArrayList<Bitmap>();
for(int i=0;i<imageList.length;i++)
{
Log.e("Image: "+i+": path", imageList[i].getAbsolutePath());
Bitmap b = BitmapFactory.decodeFile(imageList[i].getAbsolutePath());
images.add(b);
}
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1,imageList));
}
答案 0 :(得分:0)
如果您使用代码加载图片,则会遇到OutOfMemory
异常。尝试使用以下方法正确加载图像。之后,您可以填充ListView
。
private static final int IMG_BUFFER_LEN = 16384;
// R.drawable.ic_default - default drawable resource, if we cannot load drawable from provided file
// R.dimen.list_icon_size - size in dp of ImageView inside of ListView (for example, 40dp)
private Drawable extractMediaIcon(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
if (options.outWidth < 0 || options.outHeight < 0 || (options.outWidth * options.outHeight == 0)) {
return context.getResources().getDrawable(R.drawable.ic_default);
}
final int targetHeight = dp2px((int) context.getResources().getDimension(R.dimen.list_icon_size));
final int targetWidth = targetHeight;
final boolean isScaleByHeight =
Math.abs(options.outHeight - targetHeight) >= Math.abs(options.outWidth - targetWidth);
if (options.outHeight * options.outWidth * 2 >= IMG_BUFFER_LEN) {
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
final double sampleSize = isScaleByHeight
? options.outHeight / targetHeight
: options.outWidth / targetWidth;
options.inSampleSize =
(int) Math.pow(2d, Math.floor(
Math.log(sampleSize) / Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[IMG_BUFFER_LEN];
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap == null) {
return context.getResources().getDrawable(R.drawable.ic_default);
}
final double imageFactor = (double) bitmap.getWidth() / bitmap.getHeight();
final double targetFactor = (double) targetWidth / targetHeight;
bitmap = Bitmap.createScaledBitmap(
bitmap,
targetFactor > imageFactor ? bitmap.getWidth() * targetHeight / bitmap.getHeight() : targetWidth,
targetFactor > imageFactor ? targetHeight : bitmap.getHeight() * targetWidth / bitmap.getWidth(),
false);
return new BitmapDrawable(context.getResources(), bitmap);
}