Use custom adapter with ViewHolder design pattern :
grid_item
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
</LinearLayout>
MyGribView
class MyGribView extends BaseAdapter{
private Context context;
private String[] filepath;
public MyGribView(Context context,String[] filepath){
this.context=context;
this.filepath=filepath;
}
@Override
public int getCount() {
return filepath.length;
}
@Override
public Object getItem(int position) {
return filepath[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.grid_item,null);
holder.imgView = (ImageView) convertView.findViewById(R.id.imgView);
convertView.setTag(holder);
}else{
holder =(ViewHolder) convertView.getTag();
}
holder.imgView.setImageBitmap(decodeFile(filepath[position]));
return convertView;
}
class ViewHolder{
ImageView imgView;
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >=REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
}