scrollTo是滚动到指定的位置(绝对位置),view每一次invalidate的时候,滚动的坐标都是相对起始点的。
srollBy 滚动到(相对位置),view的每一次invalidate的时候,滚动的参数都是相对上一次滚动的增加 量。
两者的共同点:都是对容器内容进行滚动,滚动容器里面的所有内容。
比如viewgrop里面有好几个控件,一起开始滚动,一起结束滚动。
先看scroller的效果。
ublic class MyView extends LinearLayout {
private Scroller scroller;
private int widthPixels;
private int heightPixels;
private Button btn;
private TextView textView;
public MyView(Context context) {
super(context);
init(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
widthPixels = displayMetrics.widthPixels;
heightPixels = displayMetrics.heightPixels;
}
private void init(Context context) {
scroller = new Scroller(context, new BounceInterpolator());
this.setOrientation(LinearLayout.HORIZONTAL);
//第一个子view
textView = new TextView(context);
textView.setText("滚动侠");
textView.setTextSize(24);
LayoutParams params = new LayoutParams(100, 100);
textView.setLayoutParams(params);
textView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorAccent));
addView(textView, 0);
}
@Override
public void computeScroll() {
int finalX = scroller.getFinalX();
if (scroller.computeScrollOffset()) {
//scoller是绝地坐标,坐标值相反的
int currX = scroller.getCurrX();
int currY=scroller.getCurrY();
this.scrollTo(-currX, -currY);
temx=currX;
temY=currY;
postInvalidate();
—–增加一个view的效果—–
由此可见,scrollTo是滚动的容器里面的所有内容。
private int temx=0;
private int temY=0;
@Override
public void computeScroll() {
int finalX = scroller.getFinalX();
if (scroller.computeScrollOffset()) {
//scoller是绝地坐标,坐标值相反的
int currX = scroller.getCurrX();
int currY=scroller.getCurrY();
// this.scrollTo(-currX, -currY);
//scrllTo替换成scollBy
this.scrollBy(-currX+temx,-currY+temY);
postInvalidate();
实现的效果是一样的。
如果觉得scrollTo和scrollBy比较麻烦 的还有一种用法替换。
而且可以控制容器内的内容走不同的方向
//this.scrollTo(-currX, -currY);
//替换成下面的代码
ViewCompat.setTranslationX(btn,currX); ViewCompat.setTranslationY(textView,scroller.getCurrY());
ViewCompat.setTranslationX(textView,currX);
总结 :1.scroller.startScroll();点进去源码发现,这个方法并没有让view动起来,里面只是保存这每一帧轨迹的值,x和y。
2.scrollTo和scrollBy参数的 正负号要很容易搞混,实践出真知。
3.可以给容器内部的控件增加path动画。
4.终于明白为什么越来越多的人不愿意在csdn上写博客,因为问题太多了,作为国内最大的技术交流网站,却问题多多。