使视图沿着 RecyclerView 滚动

Make View scrolls along RecyclerView

好吧,我正在尝试制作一个类似于 Youtube 应用程序中的顶部栏。它适用于几乎所有情况,但是当我使用 RecyclerView 中的 ScrollListener 时,我遇到了问题。

如您所见,View 在滚动时不会在特定时刻改变其位置。

这是我的代码:

rvTop.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            LinearLayoutManager layoutManager = (LinearLayoutManager) layoutManagerTop;
            if(filterTopAdapter.lastSelected >= layoutManager.findFirstVisibleItemPosition() && filterTopAdapter.lastSelected <= layoutManager.findLastVisibleItemPosition()) {
                selectionLine.setVisibility(View.VISIBLE);
                final View view = rvTop.findViewHolderForAdapterPosition(filterTopAdapter.lastSelected).itemView;
                selectionLine.setTranslationX(view.getLeft() - rvTop.getScrollX());
                Log.d("Scroll", String.valueOf(view.getLeft() - rvTop.getScrollX()));
            }
            else {
                selectionLine.setVisibility(View.GONE);
            }

        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            LinearLayoutManager layoutManager = (LinearLayoutManager) layoutManagerTop;
            if(filterTopAdapter.lastSelected >= layoutManager.findFirstVisibleItemPosition() && filterTopAdapter.lastSelected <= layoutManager.findLastVisibleItemPosition()) {
                selectionLine.setVisibility(View.VISIBLE);
                final View view = rvTop.findViewHolderForAdapterPosition(filterTopAdapter.lastSelected).itemView;
                selectionLine.setTranslationX(view.getLeft() - rvTop.getScrollX());
                Log.d("Scroll", String.valueOf(view.getLeft() - rvTop.getScrollX()));
            }
            else {
                selectionLine.setVisibility(View.GONE);
            }

        }


    });

为此,您应该将 TabLayout 与 ViewPager 结合使用

你应该尝试 TabLayoutViewPager

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="stellar.kade_c.com.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="scrollable" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>