我想做一个允许我添加或删除一些照片的图像管理器。如果可能的话,我不想使用外部库。现在我尝试为显示一些图片的 GridView 做适配,这些图片是从用户使用他的相机拍摄的,我有一些问题:
- 我想为每行显示 3 张图片,我该怎么做?(现在我用 imageView.setLayoutParams(layoutParams);)
- 性能不是很好,我该如何改进呢?因为理论上我应该放大量的图片。
这是我的适配器:
public class CustomGalleryAdapter extends BaseAdapter {
private Context context;
private List<String> resources;
// Constructor
public CustomGalleryAdapter(Context context, List<String> resources){
super();
this.context = context;
this.resources = resources;
}
@Override
public int getCount() {
return resources.size();
}
@Override
public Object getItem(int position) {
return resources.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Crea un ImageView
ImageView imageView = new ImageView(context);
// Carica un file dal path dato
File imgFile = new File(resources.get(position));
// Se l'immagine esiste
if(imgFile.exists()){
// Decodifica il Bitmap
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// Setta il bitmap
imageView.setImageBitmap(myBitmap);
}
// Setta le proprietà dell'immagine
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
GridView.LayoutParams layoutParams = new GridView.LayoutParams(100, 150);
imageView.setLayoutParams(layoutParams);
// Ritorna l'immagine
return imageView;
}
}
这是我的布局:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="20dp"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
编辑:
我尝试修改,添加了 convertView 检查和 ViewHolder,但我不知道如何添加 LruCache 支持。非常感谢您的帮助!
获取视图方法:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
Log.d("IMAGES","convertView = null");
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.cell_image, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.cellImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("IMAGES","decoding...");
// Decodifica il Bitmap
Bitmap myBitmap = BitmapFactory.decodeFile(resources.get(position));
// Setta il bitmap
holder.imageView.setImageBitmap(myBitmap);
return convertView;
}
视图持有者:
class ViewHolder {
ImageView imageView;
}
细胞图像:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cellImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:adjustViewBounds="true" >
</ImageView>