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

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

效果图

在这里插入图片描述

实现思路

为了实现这一效果,需要自定义两个TextView,实现其computeScroll方法,并且结合Scroller实现平滑移动的效果。单独使用Scroller是无法实现元素移动的。

主要代码片段

  1. 自定义TextView
    private Scroller mScroller;
    public MyTestView(Context context) {
        super(context);
    }

    public MyTestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller = new Scroller(context);
    }
  1. 定义实现元素移动的方法供外部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();
    }
  1. 重写computeScroll()方法
@Override
    public void computeScroll() {
        super.computeScroll();
        if(mScroller.computeScrollOffset()){
            ((View) getParent()).scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
            //刷新重绘 
            invalidate();
        }
    }
  1. 外部调用
btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_test.scrollTo(-400,200);
                tv_test2.smoothScrollTo2(+400,200);
            }
        });
  1. 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>
  1. 需要注意的地方
    1. 需要定义两个TextView
    2. Scroller需要和computeScroll结合使用,否则无法移动元素
    3. 两个TextView需要分别包裹在两个父布局中,因为如果在一个父布局 中,运行的时候会发现两个TextView滑动的方向是相同的,猜测是和computeScroll方法中的((View) getParent()).scrollTo有关,后续再研究
  2. 结语
    采用这种方式实现文章开头的效果或许不是最好的,但是研究研究又有何妨呢
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值