在android TV端中实现水平滑动效果可以使用HorizontalScrollView来实现, 现在来介绍一下在TV端使用HorizontalScrollView时遇到的问题.
HorizontalScrollView 滑动流程
例如现在在TV端实现类似于手机launcher的功能显示所有的应用, 并使用HorizontalScrollView来实现水平滑动, 但是有这样的需求: 当应用滑动到某个子view, 这个子view并没有全部显示在屏幕上, 这个时候需要将整个应用按照你滑动的方向滑动整个屏幕的一半的距离. 如下图所示从图1到图2:
图1
图2
原生的HorizontalScrollView只能实现当滑动到显示不全的子view上时, 只是让子view显示出来:
查看HorizontalScrollView源码分析它是怎么处理这个滑动的, 在TV端对应用的控制都是通过遥控器来进行操作, 说白了就是也就是对焦点的处理(也就是对按键消息的处理), 对于在TV端开发来说, 焦点的处理非常重要. 根据android的消息处理机制, 我们查看HorizontalScrollView的dispatchKeyEvent接口:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
// Let the focused view and/or our descendants get the key first
return super.dispatchKeyEvent(event) || executeKeyEvent(event);
}
继续进入executeKeyEvent(event)方法中查看:
public boolean executeKeyEvent(KeyEvent event) {
mTempRect.setEmpty();
if (!canScroll()) {
if (isFocused()) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
View nextFocused = FocusFinder.getInstance().findNextFocus(this,
currentFocused, View.FOCUS_RIGHT);
return nextFocused != null && nextFocused != this &&
nextFocused.requestFocus(View.FOCUS_RIGHT);
}
return false;
}
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!event.isAltPressed()) {
handled = arrowScroll(View.FOCUS_LEFT);
} else {
handled = fullScroll(View.FOCUS_LEFT);
}
break;