1. 程式人生 > >VelocityTracker的簡單使用方法

VelocityTracker的簡單使用方法

/** 
 * 計算滑動速率 
 *  
 */  
public class VelocityTrackerDemoActivity extends Activity {  
  
    private static final String INFO = "手指在螢幕上滑動";  
      
    private int mMaximumVelocity;  
    private VelocityTracker mVelocityTracker;  
    private TextView mTextView;  
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        mTextView = (TextView) findViewById(R.id.textView);  
        mTextView.setText(INFO);  
          
        final ViewConfiguration configuration = ViewConfiguration.get(this);  
        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();  
  
    }  
      
      
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
  
        int action = event.getAction();  
          
        if (mVelocityTracker == null) {  
            // 獲得VelocityTracker類的一個例項物件  
            mVelocityTracker = VelocityTracker.obtain();  
        }   
        // 新增跟蹤  
        // 將當前的移動事件傳遞給VelocityTracker物件  
        mVelocityTracker.addMovement(event);  
          
        switch (action) {  
        case MotionEvent.ACTION_MOVE:  
//          mTracker.addMovement(event);  
            // 計算當前的速度  
            // 1000,初始化速率的單位 表示每秒多少畫素(pix/second),1代表每微秒多少畫素(pix/millisecond)。  
            final VelocityTracker velocityTracker = mVelocityTracker;  
            velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);  
              
            mTextView.setText(INFO + " \n橫向速率是 : "+mVelocityTracker.getXVelocity());  
            mTextView.append("\n 縱向速率是: "+mVelocityTracker.getYVelocity());  
            break;  
              
        case MotionEvent.ACTION_CANCEL:  
            // 這裡可以獲取滑動的速率  
            if (mVelocityTracker != null) {  
                mVelocityTracker.recycle();  
                mVelocityTracker = null;  
            }  
              
              
            break;  
        }  
          
        return true;  
    }  
      
}