如何使用Snaphelper更改中心元素的背景颜色

时间:2019-02-10 11:11:09

标签: android android-recyclerview

我想更改居中位置元素的背景颜色。我使用了垂直对齐帮助器,并且也检测到我的居中元素,所以我只想向居中元素添加背景颜色。

LinearSnapHelper snapHelper = new LinearSnapHelper() {

        @Override
        public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
            View centerView = findSnapView(layoutManager);
            if (centerView == null)
                return RecyclerView.NO_POSITION;

            int position = layoutManager.getPosition(centerView);
            int targetPosition = -1;
            if (layoutManager.canScrollHorizontally()) {
                if (velocityX < 0) {
                    targetPosition = position - 1;

                } else {
                    targetPosition = position + 1;
                }
            }

            if (layoutManager.canScrollVertically()) {
                if (velocityY < 0) {
                    targetPosition = position - 1;
                } else {
                    targetPosition = position + 1;
                    centerView.getBackground().setColorFilter(Color.parseColor("#000000"), PorterDuff.Mode.DARKEN);
                }
            }

            final int firstItem = 0;
            final int lastItem = layoutManager.getItemCount() - 1;
            targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
            return targetPosition;
        }
    };

}

1 个答案:

答案 0 :(得分:0)

要设置视图的背景色,可以使用各种方法check this

根据您的代码,您正在设置视图的背景色,但仅在if语句中,因此请尝试提取位于if之后的行。

...
if (layoutManager.canScrollVertically()) {
      if (velocityY < 0) {
            targetPosition = position - 1;
      } else {
            targetPosition = position + 1;
      }
}

centerView.getBackground().setColorFilter(Color.parseColor("#000000"), PorterDuff.Mode.DARKEN);

final int firstItem = 0;
final int lastItem = layoutManager.getItemCount() - 1;
targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem));
return targetPosition;
...