Rustam Ibragimov
Rustam Ibragimov

Reputation: 2707

Android horizontal carousel RecyclerView disappears

I have a vertical RecyclerView and one of its elements is horizontal RecyclerView which is an image carousel. However, when I do adapter.notifyDataSetChanged() second time on vertical RecyclerView, all images in horizontal RecyclerView become invisible (their height is 0).

Each carousel image item:

<ImageView
    android:id="@+id/iv_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"/>

Also, I am using glide in order to download images. And I see that images are downloaded and ImageView has downloaded image, but somehow its height becomes 0.

This is how it looks in the beginning: enter image description here

This is how it looks after second notifyDataSetChanged: enter image description here

Upvotes: 0

Views: 437

Answers (2)

Tiago Ornelas
Tiago Ornelas

Reputation: 1119

You can use this Widget instead of the ImageView:

public class ScaleWidthImageView extends android.support.v7.widget.AppCompatImageView {

    public ScaleWidthImageView(Context context) {
        super(context);
    }

    public ScaleWidthImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScaleWidthImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (getScaleType() == ScaleType.FIT_XY) {
            final Drawable image = getDrawable();
            if (image == null) {
                setMeasuredDimension(0, 0);
            } else {
                int width = MeasureSpec.getSize(widthMeasureSpec);
                int height = width * image.getIntrinsicHeight() / image.getIntrinsicWidth();
                setMeasuredDimension(width, height);
            }
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}

Then just use it on the XML like this:

<ScaleWidthImageView
    android:id="@+id/iv_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"/>

This widget makes the Image height dynamic depending on it's aspect ratio (which is what I assume you want).

Upvotes: 0

Qandil Tariq
Qandil Tariq

Reputation: 539

You can try multiple options: 1. Set fix height of image. 2. Maybe you are setting image in some if condition in adapter, handle that else condition also because adapter is reusing the items.

Upvotes: 0

Related Questions