Reputation: 649
I have this custom adapter for images and I want to change so it will have the view holder pattern inside of it. can anyone please help to figure out how to change my code so it will have View Holder pattern in it if it is possible at all?
public class ImageAdapter extends BaseAdapter {
private final int imageTotal;
private ArrayList<String> urlList = new ArrayList<>();
private final Context mContext;
public ImageAdapter(Context context, ArrayList<String> uList) {
mContext = context;
urlList = uList;
imageTotal = uList.size();
}
public int getCount() {
return imageTotal;
}
@Override
public String getItem(int position) {
return urlList.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setAdjustViewBounds(true);
} else {
imageView = (ImageView) convertView;
}
String url = getItem(position);
Picasso.with(mContext)
.load(url)
.placeholder(R.drawable.loader)
.fit()
.into(imageView);
return imageView;
}
}
Upvotes: 1
Views: 3353
Reputation: 4296
You are using your view as just an ImageView, so the ViewHolder pattern doesn't make sense.
But let's say you need to add an TextView to the view, so you will need to create a custom layout file with an ImageView (let's define its id as R.id.image) and a TextView (let's define its id as R.id.text).
So your code will look like this: (I will omit the unchanged parts)
public class ImageAdapter extends BaseAdapter {
static class ViewHolder {
ImageView image;
TextView text;
ViewHolder(View v) {
image = v.findViewById(R.id.image);
text = v.findViewById(R.id.text);
}
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String url = getItem(position);
Picasso.with(mContext)
.load(url)
.placeholder(R.drawable.loader)
.fit()
.into(viewHolder.image);
viewHolder.text.setText("my text");
return imageView;
}
}
The idea behind ViewHolder is to avoid the rebinding. It is also useful to separate behaviours.
But as commented by @cricket_007, you should use RecyclerView that obligates you to ViewHolder :)
Upvotes: 2