Example usage for android.view View FOCUS_RIGHT

List of usage examples for android.view View FOCUS_RIGHT

Introduction

In this page you can find the example usage for android.view View FOCUS_RIGHT.

Prototype

int FOCUS_RIGHT

To view the source code for android.view View FOCUS_RIGHT.

Click Source Link

Document

Use with #focusSearch(int) .

Usage

From source file:com.zhongsou.souyue.ui.HListView.java

@TargetApi(11)
private boolean commonKey(int keyCode, int count, KeyEvent event) {
    if (mAdapter == null || !mIsAttached) {
        return false;
    }/*  ww w.j  a  v a  2s. c om*/

    if (mDataChanged) {
        layoutChildren();
    }

    if (android.os.Build.VERSION.SDK_INT < 11) {
        return false;
    }

    boolean handled = false;
    int action = event.getAction();

    if (action != KeyEvent.ACTION_UP) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_UP:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded();
                if (!handled) {
                    while (count-- > 0) {
                        if (arrowScroll(FOCUS_UP)) {
                            handled = true;
                        } else {
                            break;
                        }
                    }
                }
            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
                handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded();
                if (!handled) {
                    while (count-- > 0) {
                        if (arrowScroll(FOCUS_DOWN)) {
                            handled = true;
                        } else {
                            break;
                        }
                    }
                }
            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
                handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (event.hasNoModifiers()) {
                handled = handleHorizontalFocusWithinListItem(View.FOCUS_LEFT);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (event.hasNoModifiers()) {
                handled = handleHorizontalFocusWithinListItem(View.FOCUS_RIGHT);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_CENTER:
        case KeyEvent.KEYCODE_ENTER:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded();
                if (!handled && event.getRepeatCount() == 0 && getChildCount() > 0) {
                    keyPressed();
                    handled = true;
                }
            }
            break;

        case KeyEvent.KEYCODE_SPACE:

            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
            } else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
                handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
            }
            handled = true;
            break;

        case KeyEvent.KEYCODE_PAGE_UP:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_UP);
            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
                handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
            }
            break;

        case KeyEvent.KEYCODE_PAGE_DOWN:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded() || pageScroll(FOCUS_DOWN);
            } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
                handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
            }
            break;

        case KeyEvent.KEYCODE_MOVE_HOME:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_UP);
            }
            break;

        case KeyEvent.KEYCODE_MOVE_END:
            if (event.hasNoModifiers()) {
                handled = resurrectSelectionIfNeeded() || fullScroll(FOCUS_DOWN);
            }
            break;

        case KeyEvent.KEYCODE_TAB:
            break;
        }
    }

    if (handled) {
        return true;
    }

    switch (action) {
    case KeyEvent.ACTION_DOWN:
        return super.onKeyDown(keyCode, event);

    case KeyEvent.ACTION_UP:
        return super.onKeyUp(keyCode, event);

    case KeyEvent.ACTION_MULTIPLE:
        return super.onKeyMultiple(keyCode, count, event);

    default: // shouldn't happen
        return false;
    }
}

From source file:cn.ismartv.tvrecyclerview.widget.StaggeredGridLayoutManager.java

/**
 * Converts a focusDirection to orientation.
 *
 * @param focusDirection One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
 *                       {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
 *                       {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
 *                       or 0 for not applicable
 * @return {@link LayoutState#LAYOUT_START} or {@link LayoutState#LAYOUT_END} if focus direction
 * is applicable to current state, {@link LayoutState#INVALID_LAYOUT} otherwise.
 *///from   w  w w. j  a va 2s. c om
private int convertFocusDirectionToLayoutDirection(int focusDirection) {
    switch (focusDirection) {
    case View.FOCUS_BACKWARD:
        if (mOrientation == VERTICAL) {
            return LayoutState.LAYOUT_START;
        } else if (isLayoutRTL()) {
            return LayoutState.LAYOUT_END;
        } else {
            return LayoutState.LAYOUT_START;
        }
    case View.FOCUS_FORWARD:
        if (mOrientation == VERTICAL) {
            return LayoutState.LAYOUT_END;
        } else if (isLayoutRTL()) {
            return LayoutState.LAYOUT_START;
        } else {
            return LayoutState.LAYOUT_END;
        }
    case View.FOCUS_UP:
        return mOrientation == VERTICAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT;
    case View.FOCUS_DOWN:
        return mOrientation == VERTICAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT;
    case View.FOCUS_LEFT:
        return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT;
    case View.FOCUS_RIGHT:
        return mOrientation == HORIZONTAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT;
    default:
        if (DEBUG) {
            Log.d(TAG, "Unknown focus request:" + focusDirection);
        }
        return LayoutState.INVALID_LAYOUT;
    }

}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

void sendScroll(final HorizontalScrollView scrollView) {
    final Handler handler = new Handler();
    new Thread(new Runnable() {
        @Override/*from ww w  .  j  a  va2  s .com*/
        public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_RIGHT);
                }
            });
        }
    }).start();
}

From source file:com.appunite.list.ListView.java

/**
 * To avoid horizontal focus searches changing the selected item, we
 * manually focus search within the selected item (as applicable), and
 * prevent focus from jumping to something within another item.
 * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
 * @return Whether this consumes the key event.
 *///from  w  ww  .jav a2 s.c om
private boolean handleHorizontalFocusWithinListItem(int direction) {
    if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) {
        throw new IllegalArgumentException("direction must be one of" + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
    }

    final int numChildren = getChildCount();
    if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
        final View selectedView = getSelectedView();
        if (selectedView != null && selectedView.hasFocus() && selectedView instanceof ViewGroup) {

            final View currentFocus = selectedView.findFocus();
            final View nextFocus = FocusFinder.getInstance().findNextFocus((ViewGroup) selectedView,
                    currentFocus, direction);
            if (nextFocus != null) {
                // do the math to get interesting rect in next focus' coordinates
                currentFocus.getFocusedRect(mTempRect);
                offsetDescendantRectToMyCoords(currentFocus, mTempRect);
                offsetRectIntoDescendantCoords(nextFocus, mTempRect);
                if (nextFocus.requestFocus(direction, mTempRect)) {
                    return true;
                }
            }
            // we are blocking the key from being handled (by returning true)
            // if the global result is going to be some other view within this
            // list.  this is to acheive the overall goal of having
            // horizontal d-pad navigation remain in the current item.
            final View globalNextFocus = FocusFinder.getInstance().findNextFocus((ViewGroup) getRootView(),
                    currentFocus, direction);
            if (globalNextFocus != null) {
                return isViewAncestorOf(globalNextFocus, this);
            }
        }
    }
    return false;
}

From source file:com.aliasapps.seq.scroller.TwoWayView.java

private boolean handleKeyEvent(int keyCode, int count, KeyEvent event) {
    if (mAdapter == null || !mIsAttached) {
        return false;
    }// ww w.j  a  v  a 2  s  . c o  m

    if (mDataChanged) {
        layoutChildren();
    }

    boolean handled = false;
    final int action = event.getAction();

    if (action != KeyEvent.ACTION_UP) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_UP:
            if (mIsVertical) {
                handled = handleKeyScroll(event, count, View.FOCUS_UP);
            } else if (KeyEventCompat.hasNoModifiers(event)) {
                handled = handleFocusWithinItem(View.FOCUS_UP);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_DOWN: {
            if (mIsVertical) {
                handled = handleKeyScroll(event, count, View.FOCUS_DOWN);
            } else if (KeyEventCompat.hasNoModifiers(event)) {
                handled = handleFocusWithinItem(View.FOCUS_DOWN);
            }
            break;
        }

        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (!mIsVertical) {
                handled = handleKeyScroll(event, count, View.FOCUS_LEFT);
            } else if (KeyEventCompat.hasNoModifiers(event)) {
                handled = handleFocusWithinItem(View.FOCUS_LEFT);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_RIGHT:
            if (!mIsVertical) {
                handled = handleKeyScroll(event, count, View.FOCUS_RIGHT);
            } else if (KeyEventCompat.hasNoModifiers(event)) {
                handled = handleFocusWithinItem(View.FOCUS_RIGHT);
            }
            break;

        case KeyEvent.KEYCODE_DPAD_CENTER:
        case KeyEvent.KEYCODE_ENTER:
            if (KeyEventCompat.hasNoModifiers(event)) {
                handled = resurrectSelectionIfNeeded();
                if (!handled && event.getRepeatCount() == 0 && getChildCount() > 0) {
                    keyPressed();
                    handled = true;
                }
            }
            break;

        case KeyEvent.KEYCODE_SPACE:
            if (KeyEventCompat.hasNoModifiers(event)) {
                handled = resurrectSelectionIfNeeded()
                        || pageScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT);
            } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
                handled = resurrectSelectionIfNeeded()
                        || fullScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT);
            }

            handled = true;
            break;

        case KeyEvent.KEYCODE_PAGE_UP:
            if (KeyEventCompat.hasNoModifiers(event)) {
                handled = resurrectSelectionIfNeeded()
                        || pageScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT);
            } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_ALT_ON)) {
                handled = resurrectSelectionIfNeeded()
                        || fullScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT);
            }
            break;

        case KeyEvent.KEYCODE_PAGE_DOWN:
            if (KeyEventCompat.hasNoModifiers(event)) {
                handled = resurrectSelectionIfNeeded()
                        || pageScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT);
            } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_ALT_ON)) {
                handled = resurrectSelectionIfNeeded()
                        || fullScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT);
            }
            break;

        case KeyEvent.KEYCODE_MOVE_HOME:
            if (KeyEventCompat.hasNoModifiers(event)) {
                handled = resurrectSelectionIfNeeded()
                        || fullScroll(mIsVertical ? View.FOCUS_UP : View.FOCUS_LEFT);
            }
            break;

        case KeyEvent.KEYCODE_MOVE_END:
            if (KeyEventCompat.hasNoModifiers(event)) {
                handled = resurrectSelectionIfNeeded()
                        || fullScroll(mIsVertical ? View.FOCUS_DOWN : View.FOCUS_RIGHT);
            }
            break;
        }
    }

    if (handled) {
        return true;
    }

    switch (action) {
    case KeyEvent.ACTION_DOWN:
        return super.onKeyDown(keyCode, event);

    case KeyEvent.ACTION_UP:
        if (!isEnabled()) {
            return true;
        }

        if (isClickable() && isPressed() && mSelectedPosition >= 0 && mAdapter != null
                && mSelectedPosition < mAdapter.getCount()) {

            final View child = getChildAt(mSelectedPosition - mFirstPosition);
            if (child != null) {
                performItemClick(child, mSelectedPosition, mSelectedRowId);
                child.setPressed(false);
            }

            setPressed(false);
            return true;
        }

        return false;

    case KeyEvent.ACTION_MULTIPLE:
        return super.onKeyMultiple(keyCode, count, event);

    default:
        return false;
    }
}

From source file:com.zhongsou.souyue.ui.HListView.java

/**
 * To avoid horizontal focus searches changing the selected item, we manually focus search within the selected item (as
 * applicable), and prevent focus from jumping to something within another item.
 *
 * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
 * @return Whether this consumes the key event.
 *//*from   ww w . j  a  v  a2  s .  co m*/
private boolean handleHorizontalFocusWithinListItem(int direction) {
    // TODO: implement this
    if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT) {
        throw new IllegalArgumentException("direction must be one of" + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
    }

    final int numChildren = getChildCount();
    if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
        final View selectedView = getSelectedView();
        if (selectedView != null && selectedView.hasFocus() && selectedView instanceof ViewGroup) {

            final View currentFocus = selectedView.findFocus();
            final View nextFocus = FocusFinder.getInstance().findNextFocus((ViewGroup) selectedView,
                    currentFocus, direction);
            if (nextFocus != null) {
                // do the math to get interesting rect in next focus' coordinates
                currentFocus.getFocusedRect(mTempRect);
                offsetDescendantRectToMyCoords(currentFocus, mTempRect);
                offsetRectIntoDescendantCoords(nextFocus, mTempRect);
                if (nextFocus.requestFocus(direction, mTempRect)) {
                    return true;
                }
            }
            // we are blocking the key from being handled (by returning true)
            // if the global result is going to be some other view within this
            // list. this is to acheive the overall goal of having
            // horizontal d-pad navigation remain in the current item.
            final View globalNextFocus = FocusFinder.getInstance().findNextFocus((ViewGroup) getRootView(),
                    currentFocus, direction);
            if (globalNextFocus != null) {
                return isViewAncestorOf(globalNextFocus, this);
            }
        }
    }
    return false;
}

From source file:com.filemanager.free.activities.MainActivity.java

public void updatePath(@NonNull final String news, boolean results, int openmode, int folder_count,
        int file_count) {

    if (news.length() == 0)
        return;/* w  ww  .  jav a  2 s .co  m*/
    if (news == null)
        return;
    if (openmode == 1 && news.startsWith("smb:/"))
        newPath = mainActivityHelper.parseSmbPath(news);
    else if (openmode == 2)
        newPath = mainActivityHelper.getIntegralNames(news);
    else
        newPath = news;
    final TextView bapath = (TextView) pathbar.findViewById(R.id.fullpath);
    final TextView animPath = (TextView) pathbar.findViewById(R.id.fullpath_anim);
    TextView textView = (TextView) pathbar.findViewById(R.id.pathname);
    if (!results) {
        textView.setText(folder_count + " " + getResources().getString(R.string.folders) + "" + " " + file_count
                + " " + getResources().getString(R.string.files));
    } else {
        bapath.setText(R.string.searchresults);
        textView.setText(R.string.empty);
        return;
    }
    final String oldPath = bapath.getText().toString();
    if (null != oldPath && oldPath.equals(newPath))
        return;

    // implement animation while setting text
    newPathBuilder = new StringBuffer().append(newPath);
    oldPathBuilder = new StringBuffer().append(oldPath);

    final Animation slideIn = AnimationUtils.loadAnimation(this, R.anim.slide_in);
    Animation slideOut = AnimationUtils.loadAnimation(this, R.anim.slide_out);

    if (newPath.length() > oldPath.length()
            && newPathBuilder.delete(oldPath.length(), newPath.length()).toString().equals(oldPath)
            && oldPath.length() != 0) {

        // navigate forward
        newPathBuilder.delete(0, newPathBuilder.length());
        newPathBuilder.append(newPath);
        newPathBuilder.delete(0, oldPath.length());
        animPath.setAnimation(slideIn);
        animPath.animate().setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        animPath.setVisibility(View.GONE);
                        bapath.setText(newPath);
                    }
                }, PATH_ANIM_END_DELAY);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                animPath.setVisibility(View.VISIBLE);
                animPath.setText(newPathBuilder.toString());
                //bapath.setText(oldPath);

                scroll.post(new Runnable() {
                    @Override
                    public void run() {
                        scroll1.fullScroll(View.FOCUS_RIGHT);
                    }
                });
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                //onAnimationEnd(animation);
            }
        }).setStartDelay(PATH_ANIM_START_DELAY).start();
    } else if (newPath.length() < oldPath.length()
            && oldPathBuilder.delete(newPath.length(), oldPath.length()).toString().equals(newPath)) {

        // navigate backwards
        oldPathBuilder.delete(0, oldPathBuilder.length());
        oldPathBuilder.append(oldPath);
        oldPathBuilder.delete(0, newPath.length());
        animPath.setAnimation(slideOut);
        animPath.animate().setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                animPath.setVisibility(View.GONE);
                bapath.setText(newPath);

                scroll.post(new Runnable() {
                    @Override
                    public void run() {
                        scroll1.fullScroll(View.FOCUS_RIGHT);
                    }
                });
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                animPath.setVisibility(View.VISIBLE);
                animPath.setText(oldPathBuilder.toString());
                bapath.setText(newPath);

                scroll.post(new Runnable() {
                    @Override
                    public void run() {
                        scroll1.fullScroll(View.FOCUS_LEFT);
                    }
                });
            }
        }).setStartDelay(PATH_ANIM_START_DELAY).start();
    } else if (oldPath.isEmpty()) {

        // case when app starts
        // FIXME: COUNTER is incremented twice on app startup
        COUNTER++;
        if (COUNTER == 2) {

            animPath.setAnimation(slideIn);
            animPath.setText(newPath);
            animPath.animate().setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    animPath.setVisibility(View.VISIBLE);
                    bapath.setText("");
                    scroll.post(new Runnable() {
                        @Override
                        public void run() {
                            scroll1.fullScroll(View.FOCUS_RIGHT);
                        }
                    });
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            animPath.setVisibility(View.GONE);
                            bapath.setText(newPath);
                        }
                    }, PATH_ANIM_END_DELAY);
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                    super.onAnimationCancel(animation);
                    //onAnimationEnd(animation);
                }
            }).setStartDelay(PATH_ANIM_START_DELAY).start();
        }

    } else {

        // completely different path
        // first slide out of old path followed by slide in of new path
        animPath.setAnimation(slideOut);
        animPath.animate().setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animator) {
                super.onAnimationStart(animator);
                animPath.setVisibility(View.VISIBLE);
                animPath.setText(oldPath);
                bapath.setText("");

                scroll.post(new Runnable() {
                    @Override
                    public void run() {
                        scroll1.fullScroll(View.FOCUS_LEFT);
                    }
                });
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                super.onAnimationEnd(animator);

                //animPath.setVisibility(View.GONE);
                animPath.setText(newPath);
                bapath.setText("");
                animPath.setAnimation(slideIn);

                animPath.animate().setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                animPath.setVisibility(View.GONE);
                                bapath.setText(newPath);
                            }
                        }, PATH_ANIM_END_DELAY);
                    }

                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        // we should not be having anything here in path bar
                        animPath.setVisibility(View.VISIBLE);
                        bapath.setText("");
                        scroll.post(new Runnable() {
                            @Override
                            public void run() {
                                scroll1.fullScroll(View.FOCUS_RIGHT);
                            }
                        });
                    }
                }).start();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                //onAnimationEnd(animation);
            }
        }).setStartDelay(PATH_ANIM_START_DELAY).start();
    }
}

From source file:com.appunite.list.HorizontalListView.java

/**
 * Handle an arrow scroll going up or down.  Take into account whether items are selectable,
 * whether there are focusable items etc.
 *
 * @param direction Either {@link android.view.View#FOCUS_LEFT} or {@link android.view.View#FOCUS_RIGHT}.
 * @return Whether any scrolling, selection or focus change occured.
 *///from   ww  w.j  ava 2  s  .  c  o  m
private boolean arrowScrollImpl(int direction) {
    if (getChildCount() <= 0) {
        return false;
    }

    View selectedView = getSelectedView();
    int selectedPos = mSelectedPosition;

    int nextSelectedPosition = (direction == View.FOCUS_RIGHT)
            ? lookForSelectablePosition(selectedPos + 1, true)
            : lookForSelectablePosition(selectedPos - 1, false);
    int amountToScroll = amountToScroll(direction, nextSelectedPosition);

    // if we are moving focus, we may OVERRIDE the default behavior
    final ArrowScrollFocusResult focusResult = mItemsCanFocus ? arrowScrollFocused(direction) : null;
    if (focusResult != null) {
        nextSelectedPosition = focusResult.getSelectedPosition();
        amountToScroll = focusResult.getAmountToScroll();
    }

    boolean needToRedraw = focusResult != null;
    if (nextSelectedPosition != INVALID_POSITION) {
        handleNewSelectionChange(selectedView, direction, nextSelectedPosition, focusResult != null);
        setSelectedPositionInt(nextSelectedPosition);
        setNextSelectedPositionInt(nextSelectedPosition);
        selectedView = getSelectedView();
        selectedPos = nextSelectedPosition;
        if (mItemsCanFocus && focusResult == null) {
            // there was no new view found to take focus, make sure we
            // don't leave focus with the old selection
            final View focused = getFocusedChild();
            if (focused != null) {
                focused.clearFocus();
            }
        }
        needToRedraw = true;
        checkSelectionChanged();
    }

    if (amountToScroll > 0) {
        scrollListItemsBy((direction == View.FOCUS_UP) ? amountToScroll : -amountToScroll);
        needToRedraw = true;
    }

    // if we didn't find a new focusable, make sure any existing focused
    // item that was panned off screen gives up focus.
    if (mItemsCanFocus && (focusResult == null) && selectedView != null && selectedView.hasFocus()) {
        final View focused = selectedView.findFocus();
        if (!isViewAncestorOf(focused, this) || distanceToView(focused) > 0) {
            focused.clearFocus();
        }
    }

    // if  the current selection is panned off, we need to remove the selection
    if (nextSelectedPosition == INVALID_POSITION && selectedView != null
            && !isViewAncestorOf(selectedView, this)) {
        selectedView = null;
        hideSelector();

        // but we don't want to set the ressurect position (that would make subsequent
        // unhandled key events bring back the item we just scrolled off!)
        mResurrectToPosition = INVALID_POSITION;
    }

    if (needToRedraw) {
        if (selectedView != null) {
            positionSelector(selectedPos, selectedView);
            mSelectedLeft = selectedView.getLeft();
        }
        if (!awakenScrollBars()) {
            invalidate();
        }
        invokeOnItemScrollListener();
        return true;
    }

    return false;
}

From source file:android.support.custom.view.VerticalViewPager.java

public boolean arrowScroll(int direction) {
    View currentFocused = findFocus();
    if (currentFocused == this)
        currentFocused = null;/*w  w  w. java2  s .c o m*/

    boolean handled = false;

    View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
    if (nextFocused != null && nextFocused != currentFocused) {
        if (direction == View.FOCUS_UP) {
            // 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 nextUp = getChildRectInPagerCoordinates(mTempRect, nextFocused).top;
            final int currUp = getChildRectInPagerCoordinates(mTempRect, currentFocused).top;

            if (currentFocused != null && nextUp >= currUp) {
                handled = pageUp();
            } 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 nextDown = getChildRectInPagerCoordinates(mTempRect, nextFocused).bottom;
            final int currDown = getChildRectInPagerCoordinates(mTempRect, currentFocused).bottom;
            if (currentFocused != null && nextDown <= currDown) {
                handled = pageDown();
            } else {
                handled = nextFocused.requestFocus();
            }
        }
    } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
        // Trying to move left and nothing there; try to page.
        handled = pageUp();
    } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
        // Trying to move right and nothing there; try to page.
        handled = pageDown();
    }
    if (handled) {
        playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
    }
    return handled;
}

From source file:cn.ismartv.tvrecyclerview.widget.RecyclerView.java

/**
 * Since RecyclerView is a collection ViewGroup that includes virtual children (items that are
 * in the Adapter but not visible in the UI), it employs a more involved focus search strategy
 * that differs from other ViewGroups./*from   w  w  w.j a v  a2 s  .  c  om*/
 * <p>
 * It first does a focus search within the RecyclerView. If this search finds a View that is in
 * the focus direction with respect to the currently focused View, RecyclerView returns that
 * child as the next focus target. When it cannot find such child, it calls
 * {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} to layout more Views
 * in the focus search direction. If LayoutManager adds a View that matches the
 * focus search criteria, it will be returned as the focus search result. Otherwise,
 * RecyclerView will call parent to handle the focus search like a regular ViewGroup.
 * <p>
 * When the direction is {@link View#FOCUS_FORWARD} or {@link View#FOCUS_BACKWARD}, a View that
 * is not in the focus direction is still valid focus target which may not be the desired
 * behavior if the Adapter has more children in the focus direction. To handle this case,
 * RecyclerView converts the focus direction to an absolute direction and makes a preliminary
 * focus search in that direction. If there are no Views to gain focus, it will call
 * {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} before running a
 * focus search with the original (relative) direction. This allows RecyclerView to provide
 * better candidates to the focus search while still allowing the view system to take focus from
 * the RecyclerView and give it to a more suitable child if such child exists.
 *
 * @param focused The view that currently has focus
 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, {@link View#FOCUS_FORWARD},
 * {@link View#FOCUS_BACKWARD} or 0 for not applicable.
 *
 * @return A new View that can be the next focus after the focused View
 */
@Override
public View focusSearch(View focused, int direction) {
    View result = mLayout.onInterceptFocusSearch(focused, direction);
    if (result != null) {
        return result;
    }
    final boolean canRunFocusFailure = mAdapter != null && mLayout != null && !isComputingLayout()
            && !mLayoutFrozen;

    final FocusFinder ff = FocusFinder.getInstance();
    if (canRunFocusFailure && (direction == View.FOCUS_FORWARD || direction == View.FOCUS_BACKWARD)) {
        // convert direction to absolute direction and see if we have a view there and if not
        // tell LayoutManager to add if it can.
        boolean needsFocusFailureLayout = false;
        if (mLayout.canScrollVertically()) {
            final int absDir = direction == View.FOCUS_FORWARD ? View.FOCUS_DOWN : View.FOCUS_UP;
            final View found = ff.findNextFocus(this, focused, absDir);
            needsFocusFailureLayout = found == null;
        }
        if (!needsFocusFailureLayout && mLayout.canScrollHorizontally()) {
            boolean rtl = mLayout.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL;
            final int absDir = (direction == View.FOCUS_FORWARD) ^ rtl ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
            final View found = ff.findNextFocus(this, focused, absDir);
            needsFocusFailureLayout = found == null;
        }
        if (needsFocusFailureLayout) {
            consumePendingUpdateOperations();
            final View focusedItemView = findContainingItemView(focused);
            if (focusedItemView == null) {
                // panic, focused view is not a child anymore, cannot call super.
                return null;
            }
            eatRequestLayout();
            mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
            resumeRequestLayout(false);
        }
        result = ff.findNextFocus(this, focused, direction);
    } else {
        result = ff.findNextFocus(this, focused, direction);
        if (result == null && canRunFocusFailure) {
            consumePendingUpdateOperations();
            final View focusedItemView = findContainingItemView(focused);
            if (focusedItemView == null) {
                // panic, focused view is not a child anymore, cannot call super.
                return null;
            }
            eatRequestLayout();
            result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
            resumeRequestLayout(false);
        }
    }
    return isPreferredNextFocus(focused, result, direction) ? result : super.focusSearch(focused, direction);
}