雖然 Android 手機並不一定會有滑鼠可以用,但 Android 平板、Android TV 卻有可能有連接到無線滑鼠,而我們如何在 Android 裝置中偵測滑鼠滾動事件呢?其實很簡單,只要在Class一開始就實做(implement)「View.OnGenericMotionListener」這個介面即可。
@Override
public boolean onGenericMotion(View v, MotionEvent event)
{
if (0 != (event.getSource() & InputDevice.SOURCE_MOUSE))
{
switch (event.getAction())
{
case MotionEvent.ACTION_SCROLL:
{
if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) < 0.0f)
{
//往下滾code
}
else
{
//往上滾code
}
return true;
}
}
}
return super.onGenericMotionEvent(event);
}
在這篇文章中,不僅實做了「View.OnGenericMotionListener」這個介面,並且覆寫了「onGenericMotion」這個監聽滑鼠滾動的抽象函式,而別忘了在程式碼一開始,就將你的 View加入這個事件的監聽。
// 將滑鼠事件加入監聽
m_listView.setOnGenericMotionListener(this);
而以上為一個基本的滾輪事件的監聽,至於如果你不是 Android 程式設計師,那麼你也可以忽略這篇囉!