Android 实现滑动的几种方法(三)scrollTo 与 scrollBy

来源:互联网 发布:centos lamp环境搭建 编辑:程序博客网 时间:2024/05/01 20:43

scrollTo(x,y): 表示移动到一个坐标点(x,y)
scrollBy(dx,dy) : 表示移动的增量为dx,dy

如果在ViewGroup中使用scrollTo和scrollBy,那么移动的是所有子View,但如果在View中使用,那么移动的将是View的内容,例如TextView。
所以,该例子不能在View中使用这两个方法来拖动这个View,该在View所在的ViewGroup中来使用这个scrollTo和scrollBy 方法: ((View) (getParent())).scrollBy(x,y);

package com.example.administrator.myapplication;import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;/** * Created by Administrator on 2015/11/22 0022. */public class MyView extends View {    int lastX;    int lastY;    public MyView(Context context) {        super(context);    }    public MyView(Context context, AttributeSet attrs) {        super(context, attrs);    }    @Override    public boolean onTouchEvent(MotionEvent event) {        int x = (int) event.getX();        int y = (int) event.getY();        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                lastX = x;                lastY = y;                break;            case MotionEvent.ACTION_MOVE:                int offx = x - lastX;                int offy = y - lastY;                /**                 * 因为参考系的选择不同,假设将屏幕scroBy(20,10)时,在水平方向上向x轴正方向平移20,              在竖直方向上向Y轴正方向平移10,可是内容却是相反的,所以要实现内容跟随手指移动而滑动,                 * 则需要将偏移量设置为负值                 */                ((View) (getParent())).scrollBy(-offx, -offy);                lastX = x;                lastY = y;                break;        }        return true;    }}
1 0