1/*
2 * Copyright (C) 2015 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
17package android.support.design.widget;
18
19import android.support.v4.view.ViewCompat;
20import android.view.View;
21
22/**
23 * Utility helper for moving a {@link android.view.View} around using
24 * {@link android.view.View#offsetLeftAndRight(int)} and
25 * {@link android.view.View#offsetTopAndBottom(int)}.
26 * <p>
27 * Also the setting of absolute offsets (similar to translationX/Y), rather than additive
28 * offsets.
29 */
30class ViewOffsetHelper {
31
32    private final View mView;
33
34    private int mLayoutTop;
35    private int mLayoutLeft;
36    private int mOffsetTop;
37    private int mOffsetLeft;
38
39    public ViewOffsetHelper(View view) {
40        mView = view;
41    }
42
43    public void onViewLayout() {
44        // Now grab the intended top
45        mLayoutTop = mView.getTop();
46        mLayoutLeft = mView.getLeft();
47
48        // And offset it as needed
49        updateOffsets();
50    }
51
52    private void updateOffsets() {
53        ViewCompat.offsetTopAndBottom(mView, mOffsetTop - (mView.getTop() - mLayoutTop));
54        ViewCompat.offsetLeftAndRight(mView, mOffsetLeft - (mView.getLeft() - mLayoutLeft));
55    }
56
57    /**
58     * Set the top and bottom offset for this {@link ViewOffsetHelper}'s view.
59     *
60     * @param offset the offset in px.
61     * @return true if the offset has changed
62     */
63    public boolean setTopAndBottomOffset(int offset) {
64        if (mOffsetTop != offset) {
65            mOffsetTop = offset;
66            updateOffsets();
67            return true;
68        }
69        return false;
70    }
71
72    /**
73     * Set the left and right offset for this {@link ViewOffsetHelper}'s view.
74     *
75     * @param offset the offset in px.
76     * @return true if the offset has changed
77     */
78    public boolean setLeftAndRightOffset(int offset) {
79        if (mOffsetLeft != offset) {
80            mOffsetLeft = offset;
81            updateOffsets();
82            return true;
83        }
84        return false;
85    }
86
87    public int getTopAndBottomOffset() {
88        return mOffsetTop;
89    }
90
91    public int getLeftAndRightOffset() {
92        return mOffsetLeft;
93    }
94}