Home > Software engineering >  Show predefined height image in RecyclerView
Show predefined height image in RecyclerView

Time:01-14

I have a recycler that show a list of images from api call. The images are different in height. When i make an API call to get the list of the images i also received the width and height of all images in pixel. My ImageView height is wrap_content with width match_parent I show the image with glide. The problem i am having is after the image is shown there will be a height change to the ImageView.

How can i use the height and width which i receive from API and is in pixel to define the imageView height before the image is shown

CodePudding user response:

You have a couple of options since you know the size of each image before it loads.

  1. If you have a placeholder, use a placeholder image when you bind view holder data that is the same size as the image to be loaded. In other words, if the image is available, use it, otherwise, use a placeholder of the same size. This way, you can keep wrap_content.

  2. If you don't have a placeholder, you can set the item view size programmatically when the view holder is created. This will result in a unique view holder for each image size. You also may be able to change the view holder size when the view is bound.

For #2, you would do something like the following in the RecyclerView adapter:

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    ItemViewHolder vh = (ItemViewHolder) holder;
    // Retrieve the known height of the image to be displayed and set the 
    // variable thisImageHeight to that value. vh.mImageView is the ImageView
    // that is being populated for this ViewHolder.
    vh.mImageView.getLayoutParams().height = thisImageHeight;
    // ... more stuff below
}
  • Related