1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.customization.picker.common.ui.view 17 18 import android.graphics.Rect 19 import android.view.View 20 import androidx.recyclerview.widget.RecyclerView 21 22 /** Item spacing used by the horizontal RecyclerView with 2 rows. */ 23 class DoubleRowListItemSpacing( 24 private val edgeItemSpacePx: Int, 25 private val itemHorizontalSpacePx: Int, 26 private val itemVerticalSpacePx: Int, 27 ) : RecyclerView.ItemDecoration() { getItemOffsetsnull28 override fun getItemOffsets( 29 outRect: Rect, 30 view: View, 31 parent: RecyclerView, 32 state: RecyclerView.State, 33 ) { 34 val itemIndex = parent.getChildAdapterPosition(view) 35 val columnIndex = itemIndex / 2 36 val isRtl = parent.layoutManager?.layoutDirection == View.LAYOUT_DIRECTION_RTL 37 38 val itemCount = parent.adapter?.itemCount ?: 0 39 val columnCount = (itemCount + 1) / 2 40 when { 41 columnCount == 1 -> { 42 outRect.left = edgeItemSpacePx 43 outRect.right = edgeItemSpacePx 44 } 45 columnIndex > 0 && columnIndex < columnCount - 1 -> { 46 outRect.left = itemHorizontalSpacePx 47 outRect.right = itemHorizontalSpacePx 48 } 49 columnIndex == 0 -> { 50 outRect.left = if (!isRtl) edgeItemSpacePx else itemHorizontalSpacePx 51 outRect.right = if (isRtl) edgeItemSpacePx else itemHorizontalSpacePx 52 } 53 columnIndex == columnCount - 1 -> { 54 outRect.right = if (!isRtl) edgeItemSpacePx else itemHorizontalSpacePx 55 outRect.left = if (isRtl) edgeItemSpacePx else itemHorizontalSpacePx 56 } 57 } 58 59 if (itemIndex % 2 == 0) { 60 outRect.bottom = itemVerticalSpacePx 61 } 62 } 63 } 64