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 androidx.core.view.ViewCompat
20 import androidx.recyclerview.widget.RecyclerView
21 
22 /** Item spacing used by the RecyclerView. */
23 class ItemSpacing(
24     private val itemSpacingDp: Int,
25 ) : RecyclerView.ItemDecoration() {
getItemOffsetsnull26     override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
27         val addSpacingToStart = itemPosition > 0
28         val addSpacingToEnd = itemPosition < (parent.adapter?.itemCount ?: 0) - 1
29         val isRtl = parent.layoutManager?.layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL
30         val density = parent.context.resources.displayMetrics.density
31         val halfItemSpacingPx = itemSpacingDp.toPx(density) / 2
32         if (!isRtl) {
33             outRect.left = if (addSpacingToStart) halfItemSpacingPx else 0
34             outRect.right = if (addSpacingToEnd) halfItemSpacingPx else 0
35         } else {
36             outRect.left = if (addSpacingToEnd) halfItemSpacingPx else 0
37             outRect.right = if (addSpacingToStart) halfItemSpacingPx else 0
38         }
39     }
40 
toPxnull41     private fun Int.toPx(density: Float): Int {
42         return (this * density).toInt()
43     }
44 
45     companion object {
46         const val TAB_ITEM_SPACING_DP = 12
47         const val ITEM_SPACING_DP = 8
48     }
49 }
50