Android水平轮播RecyclerView消失了

时间:2018-07-20 11:31:29

标签: android android-recyclerview android-imageview android-glide

我有一个垂直的RecyclerView,它的元素之一是水平的RecyclerView,它是一个图像轮播。但是,当我第二次在垂直RecyclerView上执行adapter.notifyDataSetChanged()时,水平RecyclerView中的所有图像都不可见(它们的高度为0)。

每个轮播图片项:

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

此外,我正在使用滑行来下载图像。而且我看到图像已下载并且ImageView已下载图像,但是不知何故其高度变为0。

这是开头的样子: enter image description here

这是第二次notifyDataSetChanged之后的样子: enter image description here

2 个答案:

答案 0 :(得分:0)

您可以尝试多种选择: 1.设置图像的固定高度。 2.也许您在适配器中的某些条件下设置了图像,但由于适配器正在重用这些项目,所以还要处理其他条件。

答案 1 :(得分:0)

您可以使用此小部件代替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);
        }
    }
}

然后就可以像这样在XML上使用它:

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

此小部件使图像高度根据其纵横比(这是我假设要的)而动态变化。