為了實現(xiàn)左右翻頁的效果,使用了 ViewPager,它會很方便的實現(xiàn)左右滑動后翻頁。
這時需要自己也加上兩個 button 來實現(xiàn)同樣的操作,如何實現(xiàn)呢?網(wǎng)上一篇 blog 幫了忙啦。
【Android】按鈕控制 ViewPager 的左右翻頁,保留原有的動畫效果
ViewPager 的一個公共方法 arrowScroll,查看代碼我們可以有兩個重要的發(fā)現(xiàn):
public boolean executeKeyEvent(KeyEvent event) {
boolean handled = false;
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_DPAD_LEFT://鍵盤方向鍵左鍵的控制,向左翻頁
handled = arrowScroll(FOCUS_LEFT);//FOCUS_LEFT:17
break;
case KeyEvent.KEYCODE_DPAD_RIGHT://右鍵
handled = arrowScroll(FOCUS_RIGHT);//FOCUS_RIGHT:66
break;
case KeyEvent.KEYCODE_TAB:
if (Build.VERSION.SDK_INT >= 11) {
// The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
// before Android 3.0. Ignore the tab key on those devices.
if (KeyEventCompat.hasNoModifiers(event)) {
handled = arrowScroll(FOCUS_FORWARD);//FOCUS_FORWARD:2
} else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
handled = arrowScroll(FOCUS_BACKWARD);// FOCUS_BACKWARD:1
}
}
break;
}
}
return handled;
}
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
if (currentFocused == this) currentFocused = null;
boolean handled = false;
View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
direction);
if (nextFocused != null && nextFocused != currentFocused) {
if (direction == View.FOCUS_LEFT) {
// If there is nothing to the left, or this is causing us to
// jump to the right, then what we really want to do is page left.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft >= currLeft) {
handled = pageLeft();
} else {
handled = nextFocused.requestFocus();
}
} else if (direction == View.FOCUS_RIGHT) {
// If there is nothing to the right, or this is causing us to
// jump to the left, then what we really want to do is page right.
final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
if (currentFocused != null && nextLeft <= currLeft) {
handled = pageRight();
} else {
handled = nextFocused.requestFocus();
}
}
} else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {//17 or 1
// Trying to move left and nothing there; try to page.
handled = pageLeft();
} else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {//66 or 2
// Trying to move right and nothing there; try to page.
handled = pageRight();
}
if (handled) {
playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
}
return handled;
}
也就是說,我們調(diào)用 arrowScroll 方法用參數(shù)1或者17就可以實現(xiàn)向左翻頁;參數(shù)2或66就可以實現(xiàn)向右翻頁。
后記:
當你的 UI 中有 EditText 這種獲得 focus 的 widget 時,則必須用17和66,否則要報錯。