Skip to content

Instantly share code, notes, and snippets.

@ed-george
Last active July 13, 2022 12:05
Show Gist options
  • Save ed-george/b2130d15021764a13d3b to your computer and use it in GitHub Desktop.
Save ed-george/b2130d15021764a13d3b to your computer and use it in GitHub Desktop.
Simple listener to determine if the AppBarLayout of a view is collapsed or expanded
public abstract class AppBarStateChangedListener implements AppBarLayout.OnOffsetChangedListener {
public enum State {
EXPANDED,
COLLAPSED,
IDLE
}
private State mCurrentState = State.IDLE;
@Override
public final void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset == 0) {
setCurrentStateAndNotify(appBarLayout, State.EXPANDED);
} else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
setCurrentStateAndNotify(appBarLayout, State.COLLAPSED);
} else {
setCurrentStateAndNotify(appBarLayout, State.IDLE);
}
}
private void setCurrentStateAndNotify(AppBarLayout appBarLayout, State state){
if (mCurrentState != state) {
onStateChanged(appBarLayout, state);
}
mCurrentState = state;
}
public abstract void onStateChanged(AppBarLayout appBarLayout, State state);
}
public class MainActivity extends AppCompatActivity {
private AppBarLayout appBarLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appBarLayout = findViewById(R.id.app_bar);
appBarLayout.addOnOffsetChangedListener(new AppBarStateChangedListener() {
@Override
public void onStateChanged(AppBarLayout appBarLayout, State state) {
Log.d(getClass().getCanonicalName(), state.name());
}
});
}
}
@jesselima
Copy link

It's a really good one. Very useful. Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment