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