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( 25 private val itemSpacingDp: Int, 26 ) : RecyclerView.ItemDecoration() { 27 getItemOffsetsnull28 override fun getItemOffsets( 29 outRect: Rect, 30 view: View, 31 parent: RecyclerView, 32 state: RecyclerView.State, 33 ) { 34 val itemPosition = parent.getChildAdapterPosition(view) 35 val addSpacingToStart = itemPosition > 0 36 val addSpacingToEnd = itemPosition < (parent.adapter?.itemCount ?: 0) - 1 37 val isRtl = parent.layoutManager?.layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL 38 val density = parent.context.resources.displayMetrics.density 39 val halfItemSpacingPx = itemSpacingDp.toPx(density) / 2 40 if (!isRtl) { 41 outRect.left = if (addSpacingToStart) halfItemSpacingPx else 0 42 outRect.right = if (addSpacingToEnd) halfItemSpacingPx else 0 43 } else { 44 outRect.left = if (addSpacingToEnd) halfItemSpacingPx else 0 45 outRect.right = if (addSpacingToStart) halfItemSpacingPx else 0 46 } 47 } 48 toPxnull49 private fun Int.toPx(density: Float): Int { 50 return (this * density).toInt() 51 } 52 53 companion object { 54 const val TAB_ITEM_SPACING_DP = 12 55 const val ITEM_SPACING_DP = 8 56 } 57 } 58