android - 使用 setNestedScrollingEnabled(false) 时如何避免阻止滚动本身?

标签 android android-recyclerview android-collapsingtoolbarlayout

背景

我们有一个相当复杂的布局,其中包含 CollapsingToolbarLayout,以及底部的 RecyclerView。

在某些情况下,我们通过在 RecyclerView 上调用 setNestedScrollingEnabled(boolean) 来暂时禁用 CollapsingToolbarLayout 的展开/折叠。

问题

这通常工作正常。

但是,在某些(很少见)情况下,RecyclerView 上的缓慢滚动会被半阻塞,这意味着它在向下滚动时会尝试向后滚动。就好像它有 2 个相互竞争的滚动(向上滚动和向下滚动):

enter image description here

触发它的代码如下:

res/layout/activity_scrolling.xml

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.user.myapplication.ScrollingActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/app_bar_height"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/nestedView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end">

        <Button
            android:id="@+id/disableNestedScrollingButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="disable"/>

        <Button
            android:id="@+id/enableNestedScrollingButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="enable"
            />
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

滚动 Activity .java
public class ScrollingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final RecyclerView nestedView = (RecyclerView) findViewById(R.id.nestedView);
        findViewById(R.id.disableNestedScrollingButton).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                nestedView.setNestedScrollingEnabled(false);
            }
        });
        findViewById(R.id.enableNestedScrollingButton).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View v) {
                nestedView.setNestedScrollingEnabled(true);
            }
        });
        nestedView.setLayoutManager(new LinearLayoutManager(this));
        nestedView.setAdapter(new Adapter() {
            @Override
            public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
                return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
                        android.R.layout.simple_list_item_1,
                        parent,
                        false)) {
                };
            }

            @Override
            public void onBindViewHolder(final ViewHolder holder, final int position) {
                ((TextView) holder.itemView.findViewById(android.R.id.text1)).setText("item " + position);
            }

            @Override
            public int getItemCount() {
                return 100;
            }
        });
    }

}

我试过的

一开始我还以为是别的原因(我以为是跟 DrawerLayout 的奇怪组合),后来我找到了一个最小的示例来展示它,和我想的一样:都是因为 setNestedScrollingEnabled。

我试图在 Google 的网站 (here) 上报告这个问题,希望如果它是一个真正的错误,它会得到修复。如果你想尝试一下,或者看问题的视频,去那里,因为我不能在这里上传它们(太大而且文件太多)。

我还尝试按照其他帖子的说明使用特殊标志(例如:hereherehereherehere),但没有任何帮助。事实上,他们每个人都有一个问题,无论是保持扩展模式,还是以与我不同的方式滚动。

问题
  • 这是一个已知的问题?为什么会这样?
  • 有没有办法克服这个问题?
  • 是否有替代调用 setNestedScrollingEnabled 函数的方法?一个没有任何滚动或锁定 CollapsingToolbarLayout 状态的问题?
  • 最佳答案

    这是实现与 this answer 相同目标的另一种方法。 .虽然该答案使用了反射,但该答案没有,但推理保持不变。

    为什么会这样?

    问题是 RecyclerView有时对成员变量 mScrollOffset 使用过时的值. mScrollOffset仅在 RecyclerView 中的两个位置设置: dispatchNestedPreScrolldispatchNestedScroll .我们只关心dispatchNestedPreScroll .此方法由 RecyclerView#onTouchEvent 调用当它处理 MotionEvent.ACTION_MOVE事件。

    以下来自 dispatchNestedPreScroll 的文档.

    dispatchNestedPreScroll

    boolean dispatchNestedPreScroll (int dx, int dy, int[] consumed, int[] offsetInWindow)

    Dispatch one step of a nested scroll in progress before this view consumes any portion of it.

    Nested pre-scroll events are to nested scroll events what touch intercept is to touch. dispatchNestedPreScroll offers an opportunity for the parent view in a nested scrolling operation to consume some or all of the scroll operation before the child view consumes it.

    ...

    offsetInWindow int: Optional. If not null, on return this will contain the offset in local view coordinates of this view from before this operation to after it completes. View implementations may use this to adjust expected input coordinate tracking.


    offsetInWindow实际上是一个int[2]第二个索引表示要应用于 RecyclerView 的 y 偏移由于嵌套滚动。
    RecyclerView#DispatchNestedPrescroll解析为 NestedScrollingChildHelper 中同名的方法.

    RecyclerView来电dispatchNestedPreScroll ,mScrollOffset用作 offsetInWindow争论。所以对 offsetInWindow 所做的任何更改直接更新mScrollOffset . dispatchNestedPreScroll更新 mScrollOffset只要嵌套滚动有效。如果嵌套滚动无效,则 mScrollOffset未更新并继续使用 dispatchNestedPreScroll 上次设置的值.因此,当嵌套滚动关闭时,mScrollOffset 的值立即变得陈旧,但 RecyclerView继续使用它。
    mScrollOffset[1] 的正确值从 dispatchNestedPreScroll 返回时是要为 input coordinate tracking 调整的数量(看上面)。在 RecyclerView以下几行调整 y 触摸坐标:
    mLastTouchY = y - mScrollOffset[1];
    

    如果 mScrollOffset[1]比方说,-30(因为它是陈旧的,应该为零)然后 mLastTouchY将偏离 +30 像素 (--30=+30)。这种错误计算的结果是,触摸似乎发生在屏幕下方,而不是实际发生的位置。因此,缓慢的向下滚动实际上会向上滚动,而向上滚动会更快地滚动。 (如果向下滚动的速度足以克服 30px 障碍,则向下滚动会发生,但速度会比应有的要慢。)向上滚动会过快,因为应用程序认为已经覆盖了更多空间。
    mScrollOffset将继续作为一个陈旧的变量,直到打开嵌套滚动和 dispatchNestedPreScroll再次报告 mScrollOffset 中的正确值.

    联系方式

    由于mScrollOffset[1]在某些情况下具有陈旧值,目标是在这些情况下将其设置为正确的值。当不发生嵌套滚动时,即当 AppBar 展开或折叠时,此值应为零。不幸的是,mScrollOffsetRecyclerView 的本地人并且没有二传手。访问 mScrollOffset不诉诸反射,一种习惯RecyclerView创建覆盖 dispatchNestedPreScroll .第四个参数是offsetInWindow这是我们需要改变的变量。

    陈旧的mScrollOffset每当为 RecyclerView 禁用嵌套滚动时都会发生.我们将施加的另一个条件是 AppBar 必须处于空闲状态,因此我们可以安全地说 mScrollOffset[1]应该为零。这不是问题,因为 CollapsingToolbarLayout指定 snap在滚动标志中。

    在示例应用程序中,ScrollingActivity已修改为记录 AppBar 何时展开和关闭。还创建了一个回调 ( clampPrescrollOffsetListener ),它将返回 true当我们的两个条件都满足时。我们的覆盖dispatchNestedPreScroll将调用此回调并钳制 mScrollOffset[1]true 上归零回复。
    ScrollingActivity 的更新源文件如下所示,自定义 RecyclerView - MyRecyclerView .
    必须更改 XML 布局文件以反射(reflect)自定义 MyRecyclerView .

    滚动 Activity
    public class ScrollingActivity extends AppCompatActivity
            implements MyRecyclerView.OnClampPrescrollOffsetListener {
    
        private CollapsingToolbarLayout mCollapsingToolbarLayout;
        private AppBarLayout mAppBarLayout;
        private MyRecyclerView mNestedView;
        // This variable will be true when the app bar is completely open or completely collapsed.
        private boolean mAppBarIdle = true;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_scrolling);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            mNestedView = (MyRecyclerView) findViewById(R.id.nestedView);
            mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
            mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
    
            // Set the listener for the patch code.
            mNestedView.setOnClampPrescrollOffsetListener(this);
    
            // Listener to determine when the app bar is collapsed or fully open (idle).
            mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                @Override
                public final void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                    mAppBarIdle = verticalOffset == 0
                            || verticalOffset <= appBarLayout.getTotalScrollRange();
                }
            });
            findViewById(R.id.disableNestedScrollingButton).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View v) {
                    // If the AppBar is fully expanded or fully collapsed (idle), then disable
                    // expansion and apply the patch; otherwise, set a flag to disable the expansion
                    // and apply the patch when the AppBar is idle.
                    setExpandEnabled(false);
    
                }
            });
            findViewById(R.id.enableNestedScrollingButton).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(final View v) {
                    setExpandEnabled(true);
                }
            });
            mNestedView.setLayoutManager(new LinearLayoutManager(this));
            mNestedView.setAdapter(new Adapter() {
                @Override
                public ViewHolder onCreateViewHolder(final ViewGroup parent, final int viewType) {
                    return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
                            android.R.layout.simple_list_item_1,
                            parent,
                            false)) {
                    };
                }
    
                @Override
                public void onBindViewHolder(final ViewHolder holder, final int position) {
                    ((TextView) holder.itemView.findViewById(android.R.id.text1)).setText("item " + position);
                }
    
                @Override
                public int getItemCount() {
                    return 100;
                }
            });
        }
    
        private void setExpandEnabled(boolean enabled) {
            mNestedView.setNestedScrollingEnabled(enabled);
        }
    
        // Return "true" when the app bar is idle and nested scrolling is disabled. This is a signal
        // to the custom RecyclerView to clamp the y prescroll offset to zero.
        @Override
        public boolean clampPrescrollOffsetListener() {
            return mAppBarIdle && !mNestedView.isNestedScrollingEnabled();
        }
    
        private static final String TAG = "ScrollingActivity";
    }
    

    MyRecyclerView
    public class MyRecyclerView extends RecyclerView {
        private OnClampPrescrollOffsetListener mPatchListener;
    
        public MyRecyclerView(Context context) {
            super(context);
        }
    
        public MyRecyclerView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        // Just a call to super plus code to force offsetInWindow[1] to zero if the patchlistener
        // instructs it.
        @Override
        public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
            boolean returnValue;
            int currentOffset;
            returnValue = super.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
            currentOffset = offsetInWindow[1];
            Log.d(TAG, "<<<<dispatchNestedPreScroll: " + currentOffset);
            if (mPatchListener.clampPrescrollOffsetListener() && offsetInWindow[1] != 0) {
                Log.d(TAG, "<<<<dispatchNestedPreScroll: " + currentOffset + " -> 0");
                offsetInWindow[1] = 0;
            }
            return returnValue;
        }
    
        public void setOnClampPrescrollOffsetListener(OnClampPrescrollOffsetListener patchListener) {
            mPatchListener = patchListener;
        }
    
        public interface OnClampPrescrollOffsetListener {
            boolean clampPrescrollOffsetListener();
        }
    
        private static final String TAG = "MyRecyclerView";
    }
    

    关于android - 使用 setNestedScrollingEnabled(false) 时如何避免阻止滚动本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484950/

    相关文章:

    php - 从 GCM 传递多个通知

    android - 日期为 SectionHeader 的自定义 ListView(使用自定义 SimpleCursorAdapter)

    android - 有了RecyclerView,Picasso还有必要吗?

    android - 我如何在 Android 中将数据设置到适配器中

    android - 以编程方式设置 collapsingToolbarLayout 的高度

    android - 用户不符合此购买条件 - 应用内结算

    android - Android应用程序中事件总线可以完全取代Intent吗?

    android - 协程、异步 DiffUtil 和不一致检测错误

    android - 如何在 CoordinatorLayout 中禁用 AppBarLayout 的滚动?

    Android CollapsingToolbarLayout 折叠监听器