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 lay the child out 42 layoutChild(parent, 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 protected void layoutChild(CoordinatorLayout parent, V child, int layoutDirection) { 62 // Let the parent lay it out by default 63 parent.onLayoutChild(child, layoutDirection); 64 } 65 66 public boolean setTopAndBottomOffset(int offset) { 67 if (mViewOffsetHelper != null) { 68 return mViewOffsetHelper.setTopAndBottomOffset(offset); 69 } else { 70 mTempTopBottomOffset = offset; 71 } 72 return false; 73 } 74 75 public boolean setLeftAndRightOffset(int offset) { 76 if (mViewOffsetHelper != null) { 77 return mViewOffsetHelper.setLeftAndRightOffset(offset); 78 } else { 79 mTempLeftRightOffset = offset; 80 } 81 return false; 82 } 83 84 public int getTopAndBottomOffset() { 85 return mViewOffsetHelper != null ? mViewOffsetHelper.getTopAndBottomOffset() : 0; 86 } 87 88 public int getLeftAndRightOffset() { 89 return mViewOffsetHelper != null ? mViewOffsetHelper.getLeftAndRightOffset() : 0; 90 } 91}