草庐IT

ScrollView(RecyclerView等)为什么会自动滚动原理分析,还有阻止自动滑动的解决方

WelliJohn 2023-03-28 原文
引言,有一天我在调试一个界面,xml布局里面包含Scroll View,里面嵌套了recyclerView的时候,界面一进去,就自动滚动到了recyclerView的那部分,百思不得其解,上网查了好多资料,大部分只是提到了解决的办法,但是对于为什么会这样,都没有一个很好的解释,本着对技术的负责的态度,花费了一点时间将前后理顺了下

1.首先在包含ScrollView的xml布局中,我们在一加载进来,ScrollView就自动滚动到获取焦点的子view的位置,那我们就需要看下我们activity的onCreate中执行了什么?

答:当我们在activity的onCreate方法中调用setContentView(int layRes)的时候,我们会调用LayoutInflater的inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法,这里会找到xml的rootView,然后对rootView进行rInflateChildren(parser, temp, attrs, true)加载xml的rootView下面的子View,如果是,其中会调用addView方法,我们看下addView方法:

public void addView(View child, int index, LayoutParams params) { ...... requestLayout(); invalidate(true); addViewInner(child, index, params, false); } addView的方法内部是调用了ViewGroup的addViewInner(View child, int index, LayoutParams params,boolean preventRequestLayout)方法:

android.view.ViewGroup{ ...... private void addViewInner(View child, int index, LayoutParams params, boolean preventRequestLayout) { ...... if (child.hasFocus()) { requestChildFocus(child, child.findFocus()); } ...... } } } 这里我们看到,我们在添加一个hasFocus的子view的时候,是会调用requestChildFocus方法,在这里我们需要明白view的绘制原理,是view树的层级绘制,是绘制树的最顶端,也就是子view,然后父view的机制。明白这个的话,我们再继续看ViewGroup的requestChildFocus方法,

@Override public void requestChildFocus(View child, View focused) { if (DBG) { System.out.println(this + " requestChildFocus()"); } if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) { return; } // Unfocus us, if necessary super.unFocus(focused); // We had a previous notion of who had focus. Clear it. if (mFocused != child) { if (mFocused != null) { mFocused.unFocus(focused); } mFocused = child; } if (mParent != null) { mParent.requestChildFocus(this, focused); } } 在上面会看到 mParent.requestChildFocus(this, focused);的调用,这是Android中典型的也是24种设计模式的一种(责任链模式),会一直调用,就这样,我们肯定会调用到ScrollView的requestChidlFocus方法,然后Android的ScrollView控件,重写了requestChildFocus方法:

@Override public void requestChildFocus(View child, View focused) { if (!mIsLayoutDirty) { scrollToChild(focused); } else { mChildToScrollTo = focused; } super.requestChildFocus(child, focused); } 因为在addViewInner之前调用了requestLayout()方法:

@Override public void requestLayout() { mIsLayoutDirty = true; super.requestLayout(); } 所以我们在执行requestChildFocus的时候,会进入else的判断,mChildToScrollTo = focused。

2.接下来我们继续分析下mParent.requestChildFocus(this, focused)方法?

android.view.ViewGroup{ @Override public void requestChildFocus(View child, View focused) { if (DBG) { System.out.println(this + " requestChildFocus()"); } if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) { return; } // Unfocus us, if necessary super.unFocus(focused); // We had a previous notion of who had focus. Clear it. if (mFocused != child) { if (mFocused != null) { mFocused.unFocus(focused); } mFocused = child; } if (mParent != null) { mParent.requestChildFocus(this, focused); } } } 首先,我们会判断ViewGroup的descendantFocusability属性,如果是FOCUS_BLOCK_DESCENDANTS值的话,直接就返回了(这部分后面会解释,也是android:descendantFocusability="blocksDescendants"属性能解决自动滑动的原因),我们先来看看if (mParent != null)mParent.requestChildFocus(this, focused)}成立的情况,这里会一直调用,直到调用到ViewRootImpl的requestChildFocus方法

@Override public void requestChildFocus(View child, View focused) { if (DEBUG_INPUT_RESIZE) { Log.v(mTag, "Request child focus: focus now " + focused); } checkThread(); scheduleTraversals(); } scheduleTraversals()会启动一个runnable,执行performTraversals方法进行view树的重绘制。

3.那么ScrollView为什么会滑到获取焦点的子view的位置了?

答:通过上面的分析,我们可以看到当Scrollview中包含有焦点的view的时候,最终会执行view树的重绘制,所以会调用view的onLayout方法,我们看下ScrollView的onLayout方法

android.view.ScrollView{ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); ...... if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { scrollToChild(mChildToScrollTo); } mChildToScrollTo = null; ...... } } 从第一步我们可以看到,我们在requestChildFocus方法中,是对mChildToScrollTo进行赋值了,所以这个时候,我们会进入到if判断的执行,调用scrollToChild(mChildToScrollTo)方法:

private void scrollToChild(View child) { child.getDrawingRect(mTempRect); offsetDescendantRectToMyCoords(child, mTempRect); int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); if (scrollDelta != 0) { scrollBy(0, scrollDelta); } } 很明显,当前的方法就是将ScrollView移动到获取制定的view当中,在这里我们可以明白了,为什么ScrollView会自动滑到获取焦点的子view的位置了。

4.为什么在ScrollView的子viewGroup中增加android:descendantFocusability=”blocksDescendants”属性能阻止ScrollView的自动滑动呢?

答:如第一步所说的,view的绘制原理:是view树的层级绘制,是绘制树的最顶端,也就是子view,然后父view绘制的机制,所以我们在ScrollView的直接子view设置android:descendantFocusability=”blocksDescendants”属性的时候,这个时候直接return了,就不会再继续执行父view也就是ScrollView的requestChildFocus(View child, View focused)方法了,导致下面的自动滑动就不会触发了。

@Override public void requestChildFocus(View child, View focused) { ...... if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) { return; } ...... if (mParent != null) { mParent.requestChildFocus(this, focused); } }

5.相信在这里有不少人有疑问了:如果是按照博主你的解释,是不是在ScrollView上面加android:descendantFocusability=”blocksDescendants”属性也能阻止自动滑动呢?

答:按照前面的分析的话,似乎是可以的,但是翻看ScrollView的源码,我们可以看到

private void initScrollView() { mScroller = new OverScroller(getContext()); setFocusable(true); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setWillNotDraw(false); final ViewConfiguration configuration = ViewConfiguration.get(mContext); mTouchSlop = configuration.getScaledTouchSlop(); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mOverscrollDistance = configuration.getScaledOverscrollDistance(); mOverflingDistance = configuration.getScaledOverflingDistance(); } 当你开心的设置android:descendantFocusability=”blocksDescendants”属性以为解决问题了,但是殊不知人家ScrollView的代码里面将这个descendantFocusability属性又设置成了FOCUS_AFTER_DESCENDANTS,所以你在xml中增加是没有任何作用的。

6.从上面我们分析了,ScrollView一加载就会滑动到获取焦点的子view的位置了,也明白了增加android:descendantFocusability="blocksDescendants"属性能阻止ScrollView会自动滚动到获取焦点的子view的原因,但是为什么在获取焦点的子view外面套一层view,然后增加focusableInTouchMode=true属性也可以解决这样的滑动呢?

答:我们注意到,调用addViewInner方法的时候,会先判断view.hasFocus(),其中view.hasFocus()的判断有两个规则:1.是当前的view在刚显示的时候被展示出来了,hasFocus()才可能为true;2.同一级的view有多个focus的view的话,那么只是第一个view获取焦点。 如果在布局中view标签增加focusableInTouchMode=true属性的话,意味这当我们在加载的时候,标签view的hasfocus就为true了,然而当在获取其中的子view的hasFocus方法的值的时候,他们就为false了。(这就意味着scrollview虽然会滑动,但是滑动到添加focusableInTouchMode=true属性的view的位置,如果view的位置就是填充了scrollview的话,相当于是没有滑动的,这也就是为什么在外布局增加focusableInTouchMode=true属性能阻止ScrollView会自动滚动到获取焦点的子view的原因)所以在外部套一层focusableInTouchMode=true并不是严格意义上的说法,因为虽然我们套了一层view,如果该view不是铺满的scrollview的话,很可能还是会出现自动滑动的。所以我们在套focusableInTouchMode=true属性的情况,最好是在ScrollView的直接子view 上添加就可以了。

总结

通过上面的分析,其实我们可以得到多种解决ScrollView会自动滚动到获取焦点的子view的方法,比如自定义重写Scrollview的requestChildFocus方法,直接返回return,就能中断Scrollview的自动滑动,本质上都是中断了ScrollView重写的方法requestChildFocus的进行,或者是让Scrollview中铺满ScrollView的子view获取到焦点,这样虽然滑动,但是滑动的距离只是为0罢了,相当于没有滑动罢了。** 同理我们也可以明白,如果是RecyclerView嵌套了RecyclerView,导致自动滑动的话,那么RecyclerView中也应该重写了requestChildFocus,进行自动滑动的准备。也希望大家通过阅读源码自己验证。

整理下3种方法: 第一种.

<ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusableInTouchMode="true" android:orientation="vertical"> </LinearLayout> </ScrollView> 第二种.

<ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <LinearLayout android:id="@+id/ll" android:layout_width="match_parent" android:layout_height="wrap_content" android:descendantFocusability="blocksDescendants" android:orientation="vertical"> </LinearLayout> </ScrollView> 第三种.

public class StopAutoScrollView extends ScrollView { public StopAutoScrollView(Context context) { super(context); } public StopAutoScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public StopAutoScrollView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void requestChildFocus(View child, View focused) { } } 掘金首发如果觉得有用,请点个赞或者关注下

有关ScrollView(RecyclerView等)为什么会自动滚动原理分析,还有阻止自动滑动的解决方的更多相关文章

  1. 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

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

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

  3. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  4. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby - ruby 中的 TOPLEVEL_BINDING 是什么? - 2

    它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput

  8. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐