Forked from ed-george/AppBarStateChangedListener.java
Created
February 13, 2017 12:20
-
-
Save davinctor/8450bedf10c3fb465f3116f06d0b9cf8 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