Last active
July 13, 2022 12:05
-
-
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
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 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); | |
} |
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 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()); | |
} | |
}); | |
} | |
} |
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
Thank you for the solution.