Scroller 一个移动控件的View的Helper类

scroller 是一个为了实现View平滑滑动的Helper类,通过这个类,我们可以实现控件的平滑滑动,而且使用简单

  
public class CustomView extends LinearLayout {  
  
    private Scroller mScroller;  
  
    public CustomView(Context context, AttributeSet attrs) {  
        super(context, attrs);  
        //实例化
        mScroller = new Scroller(context);  
        ImageView ivImageView = new ImageView(context);
        ivImageView.setImageResource(R.drawable.ic_fail);
        this.addView(ivImageView);
    }  
  
    //调用此方法滚动到目标位置  fx和fy是最终要停靠的位置
    public void smoothScrollTo(int fx, int fy) {  
        //这里是为了计算偏移距离,因为在下一个方法里面使用的距离是与原位置左向的距离,也就        //是说向左是正数,反正是负数
        int dx = mScroller.getFinalX() - fx;  
        int dy = mScroller.getFinalY() - fy;  
        smoothScrollBy(dx, dy);  
    }  
  
    //调用此方法设置滚动的相对偏移  
    public void smoothScrollBy(int fx, int fy) {  
  
        //设置mScroller的滚动偏移量  
        mScroller.startScroll(mScroller.getCurrX(), mScroller.getCurrY(), fx, fy, 1500);  
        invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用,否则不一定会刷新界面,看不到滚动效果  
    }  
      
    @Override  
    public void computeScroll() {  
      
        //先判断mScroller滚动是否完成  
        if (mScroller.computeScrollOffset()) {  
            //这里调用View的scrollTo()完成实际的滚动  
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());  
              
            //必须调用该方法,否则不一定能看到滚动效果  
            postInvalidate();  
        }  
        super.computeScroll();  
    }  
}  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值