Skip to content

Instantly share code, notes, and snippets.

@dmytrodanylyk
Last active September 21, 2015 12:06
Show Gist options
  • Save dmytrodanylyk/fb35176deb5114c46df6 to your computer and use it in GitHub Desktop.
Save dmytrodanylyk/fb35176deb5114c46df6 to your computer and use it in GitHub Desktop.
Fading Toolbar
public class FadingToolbar extends Toolbar {
private Drawable mToolbarBackgroundDrawable;
public FadingToolbar(Context context) {
super(context);
initView(context);
}
public FadingToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public FadingToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
mToolbarBackgroundDrawable = getContainerView().getBackground().mutate();
}
/**
* @param scrollTillOpaque - amount to scroll till toolbar is opaque
*/
public void attachToScrollView(@NonNull final ScrollView scrollView, final float scrollTillOpaque) {
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
float scrollY = scrollView.getScrollY();
float maxScroll = scrollTillOpaque - getY();
float ratio = Math.min(Math.max(scrollY, 0), maxScroll) / maxScroll;
int alpha = (int) (ratio * 255);
setBackgroundAlpha(alpha);
}
});
}
public void setBackgroundAlpha(int alpha) {
mToolbarBackgroundDrawable.setAlpha(alpha);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment