Forked from ed-george/AppBarStateChangedListener.java
Created
March 19, 2022 19:59
-
-
Save jesselima/78996c65c1e6424c6fa963b11109ba91 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()); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment