android 處理鼠標滾輪事件

android處理鼠標滾輪事件,並不是如下函數:

1) public
boolean onKeyDown(int keyCode, KeyEvent event)

2) public
boolean dispatchKeyEvent(KeyEvent event)

3) public
boolean onTouchEvent(MotionEvent event)

而是如下函數

publicboolean onGenericMotionEvent(MotionEvent event);

所有View和Activity都可重寫該函數,來自己處理滾輪事件,

如下代碼:

/**
* Implement this method to handle generic motion events.
* 實現該方法來處理一般的MotionEvent;
* 一般的motion events 描述,操縱桿的動作,鼠標honver、滾輪等
* 
* @param event The generic motion event being processed.
* @return True if the event was handled, false otherwise.
 */
	
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
//The input source is a pointing device associated with a display.
//輸入源為可顯示的指針設備,如:mouse pointing device(鼠標指針),stylus pointing device(尖筆設備)
if (0 != (event.getSource() & InputDevice.SOURCE_CLASS_POINTER)) {	
  switch (event.getAction()) {
	// process the scroll wheel movement...處理滾輪事件
	case MotionEvent.ACTION_SCROLL:	
	//獲得垂直坐標上的滾動方向,也就是滾輪向下滾
	if( event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f){	
		Log.i("fortest::onGenericMotionEvent", "down" );
			}
		//獲得垂直坐標上的滾動方向,也就是滾輪向上滾
		else{
			Log.i("fortest::onGenericMotionEvent", "up" );
		}
			return true;
		}
	}
	return super.onGenericMotionEvent(event);
}

轉載請註明出處,jiese1990。

發佈留言