草庐IT

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

coder 2023-06-08 原文

背景

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

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

问题

这通常工作正常。

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



触发它的代码如下:

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/

    有关android - 使用 setNestedScrollingEnabled(false) 时如何避免阻止滚动本身?的更多相关文章

    1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

      我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

    2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

      我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

    4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

      类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

    5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

      很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

    6. ruby - 在 Ruby 中使用匿名模块 - 2

      假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

    7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

      我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

    8. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

      我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

    9. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

      关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

    10. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

      当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

    随机推荐