Android CollapsingToolbarLayout collapse Listener

Anaximandro Andrade picture Anaximandro Andrade · Jul 28, 2015 · Viewed 63.8k times · Source

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

Answer

rciovati picture rciovati · Nov 24, 2015

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());
    }
});