【问题标题】:RecyclerView Decoration doesn't scroll correctlyRecyclerView 装饰无法正确滚动
【发布时间】:2017-07-17 18:21:25
【问题描述】:

我有一个使用简单的行分隔符装饰的 RecyclerView。

装饰很好,除了当一个新项目被添加到回收器的底部并滚动到视图中时,装饰最初被绘制在它的最终位置,然后下面的视图滚动到位,但装饰不滚动.

所需的行为是在其起始位置绘制装饰,然后与新项目一起滚动到相应位置。

以下是装饰的相关部分:

class NormalDecoration extends RecyclerView.ItemDecoration {
    private int spacing;
    private Drawable drawable;

    NormalDecoration(Context context) {
        spacing = context.getResources().getDimensionPixelOffset(R.dimen.chat_separator_height);
        drawable = ContextCompat.getDrawable(context, R.drawable.chat_divider);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if (applySpacing(view, parent)) {
            outRect.top += spacing;
        }
    }

    boolean applySpacing(View view, RecyclerView parent) {
        int position = parent.getChildAdapterPosition(view);

        return position != -1 && position < mItems.size();
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int dividerLeft = parent.getPaddingLeft();
        int dividerRight = parent.getWidth() - parent.getPaddingRight();

        for(int index = parent.getChildCount() - 1 ; index >= 0 ; --index) {
            View view = parent.getChildAt(index);

            if(applySpacing(view, parent)) {
                RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();

                int dividerTop = view.getBottom() + params.bottomMargin;
                int dividerBottom = dividerTop + spacing;

                drawable.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom);
                drawable.draw(c);
            }
        }
    }
}

我的适配器包含以下助手:

class Adapter {
    public void add(final int index, final IChatMessageItem item) {
        mItems.add(index, item);
        notifyItemInserted(index);
    }
}

以下是我如何将项目添加到导致不可接受的滚动行为的回收器:

...
adapter.add(index, item);
layout.scrollToPosition(index);
...

【问题讨论】:

    标签: java android android-recyclerview


    【解决方案1】:

    您需要分别使用view.getTranslationX()getTranslationY()getAlpha() 使装饰随着视图移动而动画化。

    如果你只是画一个分隔线,你可能想使用官方的support decoration,它也做了上面提到的。

    我也写了一篇关于这个的详细文章here

    【讨论】:

    • 我使用了几种装饰中的一种,这只是最简单的。但它们都表现出相同的行为。我去看看这篇文章。
    • @DavidBerry 这里还有一些装饰样例:github.com/bleeding182/recyclerviewItemDecorations
    • 谢谢!诀窍似乎实际上是 alpha,而不是翻译,但重要的是它有效。
    猜你喜欢
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多