Last active
September 21, 2015 12:06
-
-
Save dmytrodanylyk/fb35176deb5114c46df6 to your computer and use it in GitHub Desktop.
Fading Toolbar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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