How to properly hide&show the actionbar using the new design library API?

后端 未结 3 1122
北海茫月
北海茫月 2020-12-28 15:10

Background

Suppose I have these elements in the activity:

  • actionbar (actually a Toolbar)
  • tabs (using TabLayout )
  • ViewPager, with fr
3条回答
  •  忘掉有多难
    2020-12-28 16:09

    Based on @android developer solution which sometimes expand the app bar when list is fully scrolled I made a small change expanding or collapsing the list depending on the scrolled amount (if it's bigger than the header height then expand).

    mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.appbar_height);
    
    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            switch (newState) {
                case RecyclerView.SCROLL_STATE_IDLE:
                    mAppBar.setExpanded(mScrolledAmount < mHeaderHeight , true);
                    break;
            }
        }
    
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            mScrolledAmount += dy;
        }
    });
    

    EDIT: What works even better for me is having different thresholds to expand and collapse

         switch (newState) {
                case RecyclerView.SCROLL_STATE_IDLE:
                    if (mScrolledAmount < 50){
                        mAppBar.setExpanded(true , true);
                    }
                    if (mScrolledAmount > mHeaderHeight) {
                        mAppBar.setExpanded(false, true);
                    }
                    break;
            }
    

提交回复
热议问题