Android CollapsingToolbarLayout collapse Listener
I am using CollapsingToolBarLayout
alongside with AppBarLayout
and CoordinatorLayout
, and they are working Fine altogether. I set my Toolbar
to be fixed when I scroll up, I want to know if there is a way to change the title text of the Toolbar, when CollapsingToolBarLayout
it is collapsed.
Wrapping up, I want two different titles when scrolled and when expanded.
Thank you all in advance
I share the full implementation, based on @Frodio Beggins and @Nifhel code:
public abstract class AppBarStateChangeListener implements AppBarLayout.OnOffsetChangedListener {
public enum State {
EXPANDED,
COLLAPSED,
IDLE
}
private State mCurrentState = State.IDLE;
@Override
public final void onOffsetChanged(AppBarLayout appBarLayout, int i) {
if (i == 0) {
if (mCurrentState != State.EXPANDED) {
onStateChanged(appBarLayout, State.EXPANDED);
}
mCurrentState = State.EXPANDED;
} else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
if (mCurrentState != State.COLLAPSED) {
onStateChanged(appBarLayout, State.COLLAPSED);
}
mCurrentState = State.COLLAPSED;
} else {
if (mCurrentState != State.IDLE) {
onStateChanged(appBarLayout, State.IDLE);
}
mCurrentState = State.IDLE;
}
}
public abstract void onStateChanged(AppBarLayout appBarLayout, State state);
}
And then you can use it:
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangeListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
Log.d("STATE", state.name());
}
});
This solution works perfectly for me to detect AppBarLayout
collapsed or expanded.
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset)-appBarLayout.getTotalScrollRange() == 0)
{
// Collapsed
}
else
{
//Expanded
}
}
});
Used addOnOffsetChangedListener
on the AppBarLayout
.
Hook a OnOffsetChangedListener
to your AppBarLayout
. When the verticalOffset
reaches 0 or less than the Toolbar
height, it means that CollapsingToolbarLayout has collapsed, otherwise it is expanding or expanded.
mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if(verticalOffset == 0 || verticalOffset <= mToolbar.getHeight() && !mToolbar.getTitle().equals(mCollapsedTitle)){
mCollapsingToolbar.setTitle(mCollapsedTitle);
}else if(!mToolbar.getTitle().equals(mExpandedTitle)){
mCollapsingToolbar.setTitle(mExpandedTitle);
}
}
});