Detecting when AppBarLayout/CollapsingToolbarLayout is completely expanded

James Pizzurro picture James Pizzurro · Aug 25, 2015 · Viewed 16.7k times · Source

I have a fragment that uses the new CoordinatorLayout/AppBarLayout/CollapsingToolbarLayout paradigm, and I'd like to be able to detect when the collapsing toolbar is fully expanded so that I can perform an operation on the entire fragment it's in, e.g. popping the fragment off the stack and going to a new one, dismissing the fragment. I have the dismissing code working, I just need to know when and when not to use it.

I've experimented a bit with AppBarLayout.OnOffsetChangedListener, but didn't have much luck. Is there a way to use it to determine when things are completely expanded, or is there a more preferred method someone knows about?

Thanks in advance!

EDIT: I also see there are a couple implementations for AppBarLayout.setExpanded(...), however not AppBarLayout.getExpanded() or something similar, so I'm stumped there too.

Answer

Jimeux picture Jimeux · Sep 23, 2015

It doesn't look like there's anything in the APIs, but the following seems to be working for me. It might need testing.

boolean fullyExpanded =
    (appBarLayout.getHeight() - appBarLayout.getBottom()) == 0;

Edit: The above solution does seem to work, but since I wanted to test this condition when the appbar was scrolled, I ended up using the following solution with OnOffsetChangedListener.

class Frag extends Fragment implements AppBarLayout.OnOffsetChangedListener {

    private boolean appBarIsExpanded = true;
    private AppBarLayout appBarLayout;

    @Override 
    public void onActivityCreated(Bundle state) {
        super.onActivityCreated(state);
        appBarLayout = (AppBarLayout) getActivity().findViewById(R.id.app_bar);
    }

    @Override
    public void onResume() {
        super.onResume();
        appBarLayout.addOnOffsetChangedListener(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        appBarLayout.removeOnOffsetChangedListener(this);
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        appBarIsExpanded = (verticalOffset == 0);
    } 

}