1. 程式人生 > >Android 實現滑動的幾種方法(三)scrollTo 與 scrollBy

Android 實現滑動的幾種方法(三)scrollTo 與 scrollBy

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