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