将ItemDecoration添加到Recycler视图会导致标题收缩

时间:2016-10-05 00:31:39

标签: android xamarin android-recyclerview

我有一个使用StaggeredGridLayoutManager的RecyclerView来显示按日期划分的项目。对于每个部分(日),我有一个插入回收器视图的标题视图,在我的OnBindViewHolderAction方法中,我将标题设置为FullSpan。我的问题是,当我将我的ItemDecoration添加到RecyclerView以给出所有项目间距时,标题视图会被间距覆盖(就像添加了填充而没有增加视图大小)而不是添加边距。我不知道下一步该去哪看,任何建议都会有所帮助。感谢。

没有间隔物品装饰: enter image description here

间距项目装饰: enter image description here

应该是什么样的: enter image description here

最后一张图片与RecyclerView和ItemDecoration相同,但在GridLayoutManager上而不是StaggeredGridLayoutManager。

public void OnBindViewHolderAction(RecyclerView.ViewHolder holder, int position)
    {
        var item = _collectionAdapter.SectionedList[position];
        if (holder is ActivityFeedItemViewHolder) {
            var viewHolder = (ActivityFeedItemViewHolder)holder;
            viewHolder.Bind((ActivityFeedItemViewModel)item);
            StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams)holder.ItemView.LayoutParameters;
            layoutParams.FullSpan = false;

        }
        if (holder is RecyclerHeaderViewHolder) {
            var viewHolder = (RecyclerHeaderViewHolder)holder;
            viewHolder.Initialize(((RecyclerViewHeaderItem)item).SectionName);
            StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams)holder.ItemView.LayoutParameters;
            layoutParams.FullSpan = true;
        }
    }



public override void GetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)
    {

// STACKOVERFLOW注意:调用方法时_headerTypeId设置为0

        int pos = parent.GetChildAdapterPosition(view);

        // apply top spacing to first header only if there is one
        if (pos == 0 && _headerTypeId != -1) {
            outRect.Top = 2 * _spacing;
        }

        // these are fixed spacings for all cells
        outRect.Bottom = 2 * _spacing;
        outRect.Left = _spacing;
        outRect.Right = _spacing;

        // only apply spacing to the top row if we don't have headers
        if (_headerTypeId == -1) {

            // adjust the position index to account for headers
            for (int i = 0; i < pos; i++) {
                if (parent.GetAdapter().GetItemViewType(i) == _headerTypeId) {
                    pos--;
                }
            }

            // apply top spacing to only the top row of cells
            if (pos < _layoutManager.SpanCount) {
                outRect.Top = 2 * _spacing;
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

所以我能够通过简单地设置标题视图的高度来包装内容而不是将其设置为axml中的值(在我的情况下是32dp)来解决这个问题。感谢Eugen Pechanec。

答案 1 :(得分:0)

更改

outRect.Top = 2 * _spacing;

outRect.Top =_spacing;

如果不起作用,只需评论该行并尝试。