在RecyclerView中禁用中心项重叠

时间:2016-06-09 11:45:32

标签: android android-recyclerview

我有水平的RecyclerView图像。

当我向左滚动时,我有这样的图像顺序。

enter image description here

当我向右滚动时,我有这样的订单。

enter image description here

我需要将中央图像设置在顶部,左上方和右上方。怎么做?

我覆盖了getChildDrawingOrder方法:

@Override
    protected int getChildDrawingOrder(int childCount, int i) {
        int centerChild;

        //find center row
        if ((childCount % 2) == 0) { //even childCount number
            centerChild = childCount / 2; // if childCount 8 (actualy 0 - 7), then 4 and 4-1 = 3 is in centre.
            int otherCenterChild = centerChild - 1;
            //Which more in center?
            View child = this.getChildAt(centerChild);
            final int left = child.getLeft();
            final int right = child.getRight();
            //if this row goes through center then this
            final int absParentCenterX = getLeft() + getWidth() / 2;
            //Log.i("even", i + " from " + (childCount - 1) + ", while centerChild = " + centerChild);
            if ((left < absParentCenterX) && (right > absParentCenterX)) {
                //this child is in center line, so it is last
                //centerChild is in center, no need to change
            } else {
                centerChild = otherCenterChild;
            }
        } else {//not even - done
            centerChild = childCount / 2;
            //Log.i("not even", i + " from " + (childCount - 1) + ", while centerChild = " + centerChild);
        }

        int rez;
        //find drawIndex by centerChild
        if (i > centerChild) {
            //below center
            rez = (childCount - 1) - i + centerChild;
        } else if (i == centerChild) {
            //center row
            //draw it last
            rez = childCount - 1;
        } else {
            //above center - draw as always
            // i < centerChild
            rez = i;
        }

        //Log.i("return", "" + rez);
        return rez;
    }

我也设置了

setChildrenDrawingOrderEnabled(true);

完整代码为here

1 个答案:

答案 0 :(得分:0)

修正了添加ViewCompat.setTranslationZ(view, translationZ);

的问题
protected final void updateViews() {

    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        //setMarginsForChild(child);

        if (mAppearAnimationIsWorking)
            child.setAlpha(0);
        else
            child.setAlpha(1);

        if (mScaleUnfocusedViews && !mAppearAnimationIsWorking) {
            float scale = computeScale(child);
            child.setTranslationY(-getMeasuredHeight() * (1 - scaleFactor) / 2);
            ViewCompat.setTranslationZ(child, -getPercentageFromCenter(child));
            child.setScaleX(scale * scaleFactor * innerScale);
            child.setScaleY(scale * scaleFactor * innerScale);
        }
    }
}

getChildDrawingOrdersetChildrenDrawingOrderEnabled可以删除。