android – 当RecyclerView元素为其高度设置动画时,如何正确绘制ItemDecoration?

前端之家收集整理的这篇文章主要介绍了android – 当RecyclerView元素为其高度设置动画时,如何正确绘制ItemDecoration?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用LinearLayoutManager(垂直)的RecyclerView.我想要完成的是让项目装饰(全宽和1px高)分隔器动画与视图移动视图(translationY()正确处理)和视图更改其高度时.在我下面的当前代码中,分隔符将跳转到视图底部的未来位置,而不是动画期间的当前底部.有什么方法可以解释动画期间项目装饰的高度变化,使动画看起来更好吗?

我正在通过在RecyclerView的适配器上使用notifyItemChanged()来更改视图高度.

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public DividerItemDecoration(Context context) {
        mDivider = context.getResources().getDrawable(R.drawable.line_divider);
    }

    @Override
    public void onDrawOver(Canvas c,RecyclerView parent,RecyclerView.State state) {
        int right = parent.getWidth();
        int dividerHeight = mDivider.getIntrinsicHeight();

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount - 1; i++) {
            View child = parent.getChildAt(i);
            View nextChild = parent.getChildAt(i + 1);

            RecyclerView.LayoutParams layoutParams1 =
                    (RecyclerView.LayoutParams) child.getLayoutParams();
            RecyclerView.LayoutParams layoutParams2 =
                    (RecyclerView.LayoutParams) nextChild.getLayoutParams();
            int left = 0;
            if (layoutParams1 != null && layoutParams2 != null) {
                left = Math.min(layoutParams1.leftMargin,layoutParams2.leftMargin);
            }

            int ty = (int) (child.getTranslationY() + 0.5f);
            int top = child.getBottom() + ty;
            int bottom = top + dividerHeight;

            mDivider.setBounds(
                    left,top,right,bottom);
            mDivider.draw(c);
        }
    }
}

解决方法

我遇到过同样的问题.通过在onDraw方法添加子项转换到计算来解决这个问题,如下所示:
@Override
public void onDraw(Canvas c,RecyclerView.State state) {
    int left = parent.getPaddingLeft();
    int right = parent.getWidth() - parent.getPaddingRight();

    int childCount = parent.getChildCount();
    for (int i = 0; i < childCount - 1; i++) {
        View child = parent.getChildAt(i);
        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
        //Here is the trick!
        int top = child.getBottom() + params.bottomMargin  + Math.round(child.getTranslationY());
        int bottom = top + mDivider.getIntrinsicHeight();
        mDivider.setBounds(left,bottom);
        mDivider.draw(c);
    }
}

猜你在找的Android相关文章