`
万般皆散
  • 浏览: 17245 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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();  
    }  
}  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics