Android ScrollBy操作View与ViewGroup的区别

tech2022-07-11  189

Android中的Scroller类,相信大家都用过了。其中scrollerBy与scrollerTo的区别在许多地方都讲到过,不在赘述。 看动画相关的内容时,有一个强调点,有的动画改变的是控件内容,控件的点击事件是在原位置的,有的动画是改变控件的位置,控件的点击事件在控件动画后的位置。现在看scroller,也是强调scroller滚动的是控件内容,不是控件本身。 但是既然scroller滚动的是内容,对TexiView来说,那当然是滚动的TextView的内容,那如果是对于包含一个TextView的LinearLayout来说呢?滚动的是什么,本地做了一个小demo来证实这个问题。

Demo很简单,布局如下:

<Button android:id="@+id/scrollTo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="scrollTo"/> <LinearLayout android:id="@+id/scrollParent" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/scrollTv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="我是文字" android:textSize="26sp" android:background="#ff0000"/> </LinearLayout>

Button用来触发scroller事件,分别作用于scrollParent 和 scrollTv。为了看到效果,我们给scrollTv添加一个点击事件弹出Toast的效果。

case R.id.scrollTo: //mScrollTv.scrollBy(-10,0); mScrollParent.scrollBy(-10,0); break; case R.id.scrollTv: Toast.makeText(this,"CLICK",Toast.LENGTH_SHORT).show(); break; 我们先滚动TexiView 发现滚动的是TextView的文字内容,其位置(带红色背景)是不变的,当然其点击事件的位置还是原位置。在滚动mScrollParent 发现滚动的是整个TextView控件,其点击事件是在TextView的新位置。

所以我们得出这样的结论:Scroller滚动的确实是内容,但是对于View,比如TextView来说,滚动的是子view的内容,view位置不变;对于ViewGroup,比如LinearLayout来说,也是滚动的内容,这个内容就是ViewGroup的子view,子view的整体跟着移动。

最新回复(0)