Skip to content

Instantly share code, notes, and snippets.

@cxyxlxdm
Created October 30, 2015 09:45
Show Gist options
  • Save cxyxlxdm/eb28cef3d193ded78e57 to your computer and use it in GitHub Desktop.
Save cxyxlxdm/eb28cef3d193ded78e57 to your computer and use it in GitHub Desktop.
怎么获取 CollapsingToolbarLayout 的收缩展开状态?

给 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment