给 AppBarLayout 添加 OnOffsetChangedListener
private void setAppBarLayoutState() {
onOffsetChangedListener = new AppBarLayout.OnOffsetChangedListener() {
private State state;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (verticalOffset == 0) {
if (state != State.EXPANDED) {
//do something
//tvStarOccupation.setVisibility(View.VISIBLE);
}
state = State.EXPANDED;
} else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
if (state != State.COLLAPSED) {
//do something
//tvStarOccupation.setVisibility(View.GONE);
}
state = State.COLLAPSED;
} else {
if (state != State.IDLE) {
//do something
//tvStarOccupation.setVisibility(View.VISIBLE);
}
state = State.IDLE;
}
}
};
appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);
}
private enum State {
EXPANDED,
COLLAPSED,
IDLE
}
然后别忘了在 onResume 和 onPause 里分别在做处理。
@Override
public void onResume() {
super.onResume();
appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);
}
@Override
public void onPause() {
super.onPause();
appBarLayout.removeOnOffsetChangedListener(onOffsetChangedListener);
}