1 /* 2 * Copyright (C) 2017 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.widget; 17 18 import android.graphics.Rect; 19 import android.util.Log; 20 import android.view.View; 21 22 import androidx.recyclerview.widget.RecyclerView; 23 import androidx.recyclerview.widget.RecyclerView.ItemDecoration; 24 25 /** 26 * Decorates a grid view item with margins on each side. Note that this pads on the bottom and 27 * right, so the containing RecyclerView should add {@code paddingTop} and {@code paddingLeft} to 28 * make things look even. 29 */ 30 public class GridMarginDecoration extends ItemDecoration { 31 private static final String TAG = "GridMarginDecoration"; 32 private int horizontalMargin; 33 private int verticalMargin; 34 GridMarginDecoration(int horizontalMargin, int verticalMargin)35 public GridMarginDecoration(int horizontalMargin, int verticalMargin) { 36 this.horizontalMargin = horizontalMargin; 37 this.verticalMargin = verticalMargin; 38 } 39 40 /** 41 * Applies a GridMarginDecoration to the specified recyclerView, calculating the horizontal and 42 * vertical margin based on the view's {@code paddingLeft} and {@code paddingTop}. 43 */ applyTo(RecyclerView recyclerView)44 public static void applyTo(RecyclerView recyclerView) { 45 int horizontal = recyclerView.getPaddingLeft(); 46 int vertical = recyclerView.getPaddingTop(); 47 if (recyclerView.getPaddingRight() != 0 || recyclerView.getPaddingBottom() != 0) { 48 Log.d(TAG, "WARNING: the view being decorated has right and/or bottom padding, which will " 49 + "make the post-decoration grid unevenly padded"); 50 } 51 52 recyclerView.addItemDecoration(new GridMarginDecoration(horizontal, vertical)); 53 } 54 55 @Override getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state)56 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, 57 RecyclerView.State state) { 58 outRect.set(0, 0, horizontalMargin, verticalMargin); 59 } 60 } 61