使用Scroller实现文字从底部中间向斜上方两个对角滑动
效果图

实现思路
为了实现这一效果,需要自定义两个TextView,实现其computeScroll方法,并且结合Scroller实现平滑移动的效果。单独使用Scroller是无法实现元素移动的。
主要代码片段
- 自定义TextView
private Scroller mScroller;
public MyTestView(Context context) {
super(context);
}
public MyTestView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
- 定义实现元素移动的方法供外部activity调用
public void scrollTo(int destX,int destY){
int scrollX=getScrollX();
int scrollY=getScrollY();
int deltax=destX-scrollX;
int deltay=destY-scrollY;
//在2s内完成移动
mScroller.startScroll(scrollX,scrollY,deltax,deltay,2000);
// mScroller.startScroll(scrollY,0,deltax,0,2000);
invalidate();
}
- 重写computeScroll()方法
@Override
public void computeScroll() {
super.computeScroll();
if(mScroller.computeScrollOffset()){
((View) getParent()).scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
//刷新重绘
invalidate();
}
}
- 外部调用
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv_test.scrollTo(-400,200);
tv_test2.smoothScrollTo2(+400,200);
}
});
- xml布局
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:gravity="center_horizontal">
<com.example.myapplication.MyTestView
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
android:textSize="10sp"
android:layout_gravity="bottom|center_horizontal"/>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_test2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:gravity="center_horizontal">
<com.example.myapplication.MyTestView2
android:id="@+id/tv_test2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello23"
android:textSize="10sp"
android:layout_gravity="bottom|center_horizontal"/>
</LinearLayout>
- 需要注意的地方
- 需要定义两个TextView
- Scroller需要和computeScroll结合使用,否则无法移动元素
- 两个TextView需要分别包裹在两个父布局中,因为如果在一个父布局 中,运行的时候会发现两个TextView滑动的方向是相同的,猜测是和computeScroll方法中的((View) getParent()).scrollTo有关,后续再研究
- 结语
采用这种方式实现文章开头的效果或许不是最好的,但是研究研究又有何妨呢
本文介绍如何使用Scroller和自定义TextView实现文字从底部中间向斜上方两个对角滑动的特效。通过重写computeScroll方法并结合Scroller,实现平滑移动效果。

803

被折叠的 条评论
为什么被折叠?



