Skip to content

Instantly share code, notes, and snippets.

@technoir42
Created October 18, 2016 20:52
Show Gist options
  • Save technoir42/b35b3794a1c150e7daae5602af2e761b to your computer and use it in GitHub Desktop.
Save technoir42/b35b3794a1c150e7daae5602af2e761b to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.support.annotation.Keep;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
@Keep
public class ViewCenteringBehavior extends CoordinatorLayout.Behavior<View> {
public ViewCenteringBehavior() {
}
public ViewCenteringBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof AppBarLayout;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
return updateViewPosition(parent, child, (AppBarLayout) dependency);
}
@Override
public boolean onLayoutChild(CoordinatorLayout parent, View child, int layoutDirection) {
parent.onLayoutChild(child, layoutDirection);
AppBarLayout appBarLayout = null;
for (View dependency : parent.getDependencies(child)) {
if (dependency instanceof AppBarLayout) {
appBarLayout = (AppBarLayout) dependency;
break;
}
}
updateViewPosition(parent, child, appBarLayout);
return true;
}
private boolean updateViewPosition(CoordinatorLayout parent, View child, @Nullable AppBarLayout appBarLayout) {
final int top = appBarLayout != null ? appBarLayout.getBottom() : 0;
final int topOffset = (top + parent.getBottom() - child.getHeight()) / 2 - child.getTop();
final int leftOffset = (parent.getWidth() - child.getWidth()) / 2 - child.getLeft();
if (topOffset != 0) {
ViewCompat.offsetTopAndBottom(child, topOffset);
}
if (leftOffset != 0) {
ViewCompat.offsetLeftAndRight(child, leftOffset);
}
return topOffset != 0 || leftOffset != 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment