以下是我用于从设备存储卡将图像文件夹加载到我的应用程序中的代码。
在此代码中,我使用文件对象获取图像路径,并将该对象传递给适配器,我正在设置图像。
File file= new File(Environment.getExternalStorageDirectory()
+ File.separator + "Pictures" + File.separator + "test");
final File[] files = file.listFiles();
for (File _file : files) {
myAdapter.add(_file.getAbsolutePath());
}
但我发现有混蛋而我打开这个特殊片段。因为一次加载所有图片并显示它们需要时间,并且在滚动页面时找到相同的抽搐。
这是我的适配器类外观,
public class ImageAdapter extends BaseAdapter{
public Context mContext;
ArrayList<String> itemList = new ArrayList<>();
public ImageAdapter(Context c) {
mContext = c;
}
public void add(String path) {
itemList.add(path);
}
@Override
public int getCount() {
return itemList.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(180dp,180dp);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(EIGHT, EIGHT, EIGHT, EIGHT);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 180dp,180dp);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
答案 0 :(得分:0)
自己解码位图是非常好的,但你不应该在UI线程中这样做,使用像Picasso或Glide这样的库,或者如果你真的想自己在另一个线程中做它,解码位图是昂贵的并导致滞后
答案 1 :(得分:0)
使用Picasso或后台线程加载图像。 此外,使用Picasso,您可以在加载图像时设置占位符,在出现错误时设置替代图像,使用合适的图像等。结果将非常专业。
ImageView imageView = (ImageView) FindViewById(...);
Picasso.with(getActivity())
.load(new File("path-to-file/file.png"))
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.fit()
.into(imageView);