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