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.content.Context; 20import android.util.AttributeSet; 21import android.view.View; 22 23/** 24 * Behavior will automatically sets up a {@link ViewOffsetHelper} on a {@link View}. 25 */ 26class ViewOffsetBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { 27 28 private ViewOffsetHelper mViewOffsetHelper; 29 30 private int mTempTopBottomOffset = 0; 31 private int mTempLeftRightOffset = 0; 32 33 public ViewOffsetBehavior() {} 34 35 public ViewOffsetBehavior(Context context, AttributeSet attrs) { 36 super(context, attrs); 37 } 38 39 @Override 40 public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) { 41 // First let the parent lay it out 42 parent.onLayoutChild(child, layoutDirection); 43 44 if (mViewOffsetHelper == null) { 45 mViewOffsetHelper = new ViewOffsetHelper(child); 46 } 47 mViewOffsetHelper.onViewLayout(); 48 49 if (mTempTopBottomOffset != 0) { 50 mViewOffsetHelper.setTopAndBottomOffset(mTempTopBottomOffset); 51 mTempTopBottomOffset = 0; 52 } 53 if (mTempLeftRightOffset != 0) { 54 mViewOffsetHelper.setLeftAndRightOffset(mTempLeftRightOffset); 55 mTempLeftRightOffset = 0; 56 } 57 58 return true; 59 } 60 61 public boolean setTopAndBottomOffset(int offset) { 62 if (mViewOffsetHelper != null) { 63 return mViewOffsetHelper.setTopAndBottomOffset(offset); 64 } else { 65 mTempTopBottomOffset = offset; 66 } 67 return false; 68 } 69 70 public boolean setLeftAndRightOffset(int offset) { 71 if (mViewOffsetHelper != null) { 72 return mViewOffsetHelper.setLeftAndRightOffset(offset); 73 } else { 74 mTempLeftRightOffset = offset; 75 } 76 return false; 77 } 78 79 public int getTopAndBottomOffset() { 80 return mViewOffsetHelper != null ? mViewOffsetHelper.getTopAndBottomOffset() : 0; 81 } 82 83 public int getLeftAndRightOffset() { 84 return mViewOffsetHelper != null ? mViewOffsetHelper.getLeftAndRightOffset() : 0; 85 } 86}