RecyclerView滑动隐藏Toolbar

实现方式:
1.CoordinatorLayout+AppbarLayout
优点:简单
缺点:列表的item不满一屏时,上滑时toolbar还是会隐藏

2.通过监听recycler的滑动

——2.1首先搞一个toolbar那么高的头布局占位

  searchAdapter = new SearchAdapter();
        View headerView = LayoutInflater.from(this).inflate(R.layout.item_search_header, (ViewGroup) rvSearch.getParent(), false);
        searchAdapter.addHeaderView(headerView);
        rvSearch.setAdapter(searchAdapter);



——2.2监听Recycler的滑动

   /**
         * 实现RecyclerView上下滑动的显示和隐藏****
         *
         * */
        rvSearch.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private static final int HIDE_THRESHOLD = 20;
            private int scrolledDistance = 0;
            private boolean controlsVisible = true;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.e(TAG, "onScrolled dy: " + dy);
                Log.e(TAG, "onScrolled dx: " + dx);
                Log.e(TAG, "-------------------- onScrolled: --------------------");
                int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
                if (firstVisibleItem >= 1) {
                    if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
                        // 隐藏toolbar
                        hideViews();
                        controlsVisible = false;
                        scrolledDistance = 0;
                    } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
                        // 显示toolbar
                        showViews();
                        controlsVisible = true;
                        scrolledDistance = 0;
                    }
                    if ((controlsVisible && dy > 0) || (!controlsVisible && dy < 0)) {
                        scrolledDistance += dy;
                    }
                }
            }
        });

    }


    private void hideViews() {
        toolbar.animate().translationY(-toolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));
    }

    private void showViews() {
        toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
    }

你可能感兴趣的:(RecyclerView滑动隐藏Toolbar)