在看RecyclerView源码的时候发现有一个方法实现,叫onGenericMotionEvent(MotionEvent event),从方法注释看是专门响应一些外接设备的操作的,比如游戏手柄,鼠标,滚轮,触控板等。从RecyclerView的onGenericMotionEvent实现来看,确实也是如此。
代码如下:
public boolean onGenericMotionEvent(MotionEvent event) {
if (mLayout == null) {
return false;
}
if (mLayoutFrozen) {
return false;
}
if (event.getAction() == MotionEventCompat.ACTION_SCROLL) {
final float vScroll, hScroll;
if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) {
if (mLayout.canScrollVertically()) {
// Inverse the sign of the vertical scroll to align the scroll orientation
// with AbsListView.
vScroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
} else {
vScroll = 0f;
}
if (mLayout.canScrollHorizontally()) {
hScroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
} else {
hScroll = 0f;
}
} else if ((event.getSource() & InputDeviceCompat.SOURCE_ROTARY_ENCODER) != 0) {
final float axisScroll = event.getAxisValue(MotionEventCompat.AXIS_SCROLL);
if (mLayout.canScrollVertically()) {
// Invert the sign of the vertical scroll to align the scroll orientation
// with AbsListView.
vScroll = -axisScroll;
hScroll = 0f;
} else if (mLayout.canScrollHorizontally()) {
vScroll = 0f;
hScroll = axisScroll;
} else {
vScroll = 0f;
hScroll = 0f;
}
} else {
vScroll = 0f;
hScroll = 0f;
}
if (vScroll != 0 || hScroll != 0) {
scrollByInternal((int) (hScroll * mScaledHorizontalScrollFactor),
(int) (vScroll * mScaledVerticalScrollFactor), event);
}
}
return false;
}
RecyclerView只正对滚动事件做了处理,然后我们可以通过event.getSource()
方法获取到是哪个外接设备触发的事件,有兴趣的同学可以看一下。