Example usage for android.view View clearFocus

List of usage examples for android.view View clearFocus

Introduction

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

Prototype

public void clearFocus() 

Source Link

Document

Called when this view wants to give up focus.

Usage

From source file:com.zyk.launcher.AsyncTaskCallback.java

public void beginDragShared(View child, DragSource source) {
    ///*from   ww  w  .ja v a 2s .c om*/
    child.clearFocus();
    //??false?false?
    child.setPressed(false);

    //???????
    // The outline is used to visualize where the item will land if dropped
    mDragOutline = createDragOutline(child, Workspace.DRAG_BITMAP_PADDING);

    //        mLauncher.onDragStarted(child);
    // The drag bitmap follows the touch point around on the screen
    AtomicInteger padding = new AtomicInteger(Workspace.DRAG_BITMAP_PADDING);
    final Bitmap b = Utils.createDragBitmap(child, padding);

    final int bmpWidth = b.getWidth();
    final int bmpHeight = b.getHeight();

    float scale = mLauncher.getDragLayer().getLocationInDragLayer(child, mTempXY);
    int dragLayerX = Math.round(mTempXY[0] - (bmpWidth - scale * child.getWidth()) / 2);
    int dragLayerY = Math.round(mTempXY[1] - (bmpHeight - scale * bmpHeight) / 2 - padding.get() / 2);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    Point dragVisualizeOffset = null;
    Rect dragRect = null;
    if (child instanceof BubbleTextView) {
        int iconSize = grid.iconSizePx;
        int top = child.getPaddingTop();
        int left = (bmpWidth - iconSize) / 2;
        int right = left + iconSize;
        int bottom = top + iconSize;
        dragLayerY += top;
        // Note: The drag region is used to calculate drag layer offsets, but the
        // dragVisualizeOffset in addition to the dragRect (the size) to position the outline.
        dragVisualizeOffset = new Point(-padding.get() / 2, padding.get() / 2);
        dragRect = new Rect(left, top, right, bottom);
    } else if (child instanceof FolderIcon) {
        int previewSize = grid.folderIconSizePx;
        dragRect = new Rect(0, child.getPaddingTop(), child.getWidth(), previewSize);
    }

    // Clear the pressed state if necessary
    if (child instanceof BubbleTextView) {
        BubbleTextView icon = (BubbleTextView) child;
        icon.clearPressedBackground();
    }

    if (child.getTag() == null || !(child.getTag() instanceof ItemInfo)) {
        String msg = "Drag started with a view that has no tag set. This "
                + "will cause a crash (issue 11627249) down the line. " + "View: " + child + "  tag: "
                + child.getTag();
        throw new IllegalStateException(msg);
    }

    DragView dv = mDragController.startDrag(b, dragLayerX, dragLayerY, source, child.getTag(),
            DragController.DRAG_ACTION_MOVE, dragVisualizeOffset, dragRect, scale);
    dv.setIntrinsicIconScaleFactor(source.getIntrinsicIconScaleFactor());

    if (child.getParent() instanceof ShortcutAndWidgetContainer) {
        mDragSourceInternal = (ShortcutAndWidgetContainer) child.getParent();
    }

    b.recycle();
}

From source file:org.bangbang.support.v4.widget.HListView.java

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

        View selectedView = getSelectedView();

        int nextSelectedPosition = lookForSelectablePositionOnScreen(direction);
        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();
            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_LEFT) ? 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 (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(selectedView);
                mSelectedTop = selectedView.getTop();
            }
            invalidate();
            invokeOnItemScrollListener();
            return true;
        }

        return false;
    }

From source file:org.bangbang.support.v4.widget.HListView.java

@Override
    protected void layoutChildren() {
        final boolean blockLayoutRequests = mBlockLayoutRequests;
        if (!blockLayoutRequests) {
            mBlockLayoutRequests = true;
        } else {//from  ww w. j av a  2s.c om
            return;
        }

        try {
            super.layoutChildren();

            invalidate();

            if (mAdapter == null) {
                resetList();
                invokeOnItemScrollListener();
                return;
            }

            int childrenLeft = mListPadding.left;
            int childrenRight = getRight() - getLeft() - mListPadding.right;

            int childCount = getChildCount();
            int index;
            int delta = 0;

            View sel;
            View oldSel = null;
            View oldFirst = null;
            View newSel = null;

            View focusLayoutRestoreView = null;

            // Remember stuff we will need down below
            switch (mLayoutMode) {
            case LAYOUT_SET_SELECTION:
                index = mNextSelectedPosition - mFirstPosition;
                if (index >= 0 && index < childCount) {
                    newSel = getChildAt(index);
                }
                break;
            case LAYOUT_FORCE_TOP:
            case LAYOUT_FORCE_BOTTOM:
            case LAYOUT_SPECIFIC:
            case LAYOUT_SYNC:
                break;
            case LAYOUT_MOVE_SELECTION:
            default:
                // Remember the previously selected view
                index = mSelectedPosition - mFirstPosition;
                if (index >= 0 && index < childCount) {
                    oldSel = getChildAt(index);
                }

                // Remember the previous first child
                oldFirst = getChildAt(0);

                if (mNextSelectedPosition >= 0) {
                    delta = mNextSelectedPosition - mSelectedPosition;
                }

                // Caution: newSel might be null
                newSel = getChildAt(index + delta);
            }

            boolean dataChanged = mDataChanged;
            if (dataChanged) {
                handleDataChanged();
            }

            // Handle the empty set by removing all views that are visible
            // and calling it a day
            if (mItemCount == 0) {
                resetList();
                invokeOnItemScrollListener();
                return;
            } else if (mItemCount != mAdapter.getCount()) {
                throw new IllegalStateException("The content of the adapter has changed but "
                        + "ListView did not receive a notification. Make sure the content of "
                        + "your adapter is not modified from a background thread, but only "
                        + "from the UI thread.");
            }

            setSelectedPositionInt(mNextSelectedPosition);

            // Pull all children into the RecycleBin.
            // These views will be reused if possible
            final int firstPosition = mFirstPosition;
            final RecycleBin recycleBin = mRecycler;

            // reset the focus restoration
            View focusLayoutRestoreDirectChild = null;

            // Don't put header or footer views into the Recycler. Those are
            // already cached in mHeaderViews;
            if (dataChanged) {
                for (int i = 0; i < childCount; i++) {
                    recycleBin.addScrapView(getChildAt(i));
                    if (ViewDebug.TRACE_RECYCLER) {
                        ViewDebug.trace(getChildAt(i), ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
                    }
                }
            } else {
                recycleBin.fillActiveViews(childCount, firstPosition);
            }

            // take focus back to us temporarily to avoid the eventual
            // call to clear focus when removing the focused child below
            // from messing things up when ViewRoot assigns focus back
            // to someone else
            final View focusedChild = getFocusedChild();
            if (focusedChild != null) {
                // TODO: in some cases focusedChild.getParent() == null

                // we can remember the focused view to restore after relayout if the
                // data hasn't changed, or if the focused position is a header or footer
                if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
                    focusLayoutRestoreDirectChild = focusedChild;
                    // remember the specific view that had focus
                    focusLayoutRestoreView = findFocus();
                    if (focusLayoutRestoreView != null) {
                        // tell it we are going to mess with it
                        focusLayoutRestoreView.onStartTemporaryDetach();
                    }
                }
                requestFocus();
            }

            // Clear out old views
            //removeAllViewsInLayout();
            detachAllViewsFromParent();

            switch (mLayoutMode) {
            case LAYOUT_SET_SELECTION:
                if (newSel != null) {
                    sel = fillFromSelection(newSel.getLeft(), childrenLeft, childrenRight);
                } else {
                    sel = fillFromMiddle(childrenLeft, childrenRight);
                }
                break;
            case LAYOUT_SYNC:
                sel = fillSpecific(mSyncPosition, mSpecificTop);
                break;
            case LAYOUT_FORCE_BOTTOM:
                sel = fillUp(mItemCount - 1, childrenRight);
                adjustViewsUpOrDown();
                break;
            case LAYOUT_FORCE_TOP:
                mFirstPosition = 0;
                sel = fillFromTop(childrenLeft);
                adjustViewsUpOrDown();
                break;
            case LAYOUT_SPECIFIC:
                sel = fillSpecific(reconcileSelectedPosition(), mSpecificLeft);
                break;
            case LAYOUT_MOVE_SELECTION:
                sel = moveSelection(oldSel, newSel, delta, childrenLeft, childrenRight);
                break;
            default:
                if (childCount == 0) {
                    if (!mStackFromBottom) {
                        final int position = lookForSelectablePosition(0, true);
                        setSelectedPositionInt(position);
                        sel = fillFromTop(childrenLeft);
                    } else {
                        final int position = lookForSelectablePosition(mItemCount - 1, false);
                        setSelectedPositionInt(position);
                        sel = fillUp(mItemCount - 1, childrenRight);
                    }
                } else {
                    if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
                        sel = fillSpecific(mSelectedPosition, oldSel == null ? childrenLeft : oldSel.getLeft());
                    } else if (mFirstPosition < mItemCount) {
                        sel = fillSpecific(mFirstPosition, oldFirst == null ? childrenLeft : oldFirst.getLeft());
                    } else {
                        sel = fillSpecific(0, childrenLeft);
                    }
                }
                break;
            }

            // Flush any cached views that did not get reused above
            recycleBin.scrapActiveViews();

            if (sel != null) {
                // the current selected item should get focus if items
                // are focusable
                if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
                    final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild
                            && focusLayoutRestoreView.requestFocus()) || sel.requestFocus();
                    if (!focusWasTaken) {
                        // selected item didn't take focus, fine, but still want
                        // to make sure something else outside of the selected view
                        // has focus
                        final View focused = getFocusedChild();
                        if (focused != null) {
                            focused.clearFocus();
                        }
                        positionSelector(sel);
                    } else {
                        sel.setSelected(false);
                        mSelectorRect.setEmpty();
                    }
                } else {
                    positionSelector(sel);
                }
                mSelectedTop = sel.getTop();
            } else {
                mSelectedTop = 0;
                mSelectorRect.setEmpty();

                // even if there is not selected position, we may need to restore
                // focus (i.e. something focusable in touch mode)
                if (hasFocus() && focusLayoutRestoreView != null) {
                    focusLayoutRestoreView.requestFocus();
                }
            }

            // tell focus view we are done mucking with it, if it is still in
            // our view hierarchy.
            if (focusLayoutRestoreView != null && focusLayoutRestoreView.getWindowToken() != null) {
                focusLayoutRestoreView.onFinishTemporaryDetach();
            }

            mLayoutMode = LAYOUT_NORMAL;
            mDataChanged = false;
            mNeedSync = false;
            setNextSelectedPositionInt(mSelectedPosition);

            updateScrollIndicators();

            if (mItemCount > 0) {
                checkSelectionChanged();
            }

            invokeOnItemScrollListener();
        } finally {
            if (!blockLayoutRequests) {
                mBlockLayoutRequests = false;
            }
        }
    }

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 w  w w  . jav  a2  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:com.awrtechnologies.carbudgetsales.hlistview.widget.HListView.java

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

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

    int nextSelectedPosition = lookForSelectablePositionOnScreen(direction);
    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:com.appunite.list.ListView.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_UP} or {@link android.view.View#FOCUS_DOWN}.
 * @return Whether any scrolling, selection or focus change occured.
 *//*from www.  ja v  a  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_DOWN) ? 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);
            mSelectedTop = selectedView.getTop();
        }
        if (!awakenScrollBars()) {
            invalidate();
        }
        invokeOnItemScrollListener();
        return true;
    }

    return false;
}

From source file:com.awrtechnologies.valor.valorfireplace.hlistview.widget.HListView.java

@Override
protected void layoutChildren() {
    final boolean blockLayoutRequests = mBlockLayoutRequests;
    if (!blockLayoutRequests) {
        mBlockLayoutRequests = true;/* w ww.  j  av  a 2s.c o m*/
    } else {
        return;
    }

    try {
        super.layoutChildren();

        invalidate();

        if (mAdapter == null) {
            resetList();
            invokeOnItemScrollListener();
            return;
        }

        int childrenLeft = mListPadding.left;
        int childrenRight = getRight() - getLeft() - mListPadding.right;

        int childCount = getChildCount();
        int index = 0;
        int delta = 0;

        View sel;
        View oldSel = null;
        View oldFirst = null;
        View newSel = null;

        View focusLayoutRestoreView = null;

        // AccessibilityNodeInfo accessibilityFocusLayoutRestoreNode = null;
        // View accessibilityFocusLayoutRestoreView = null;
        // int accessibilityFocusPosition = INVALID_POSITION;

        // Remember stuff we will need down below
        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            index = mNextSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                newSel = getChildAt(index);
            }
            break;
        case LAYOUT_FORCE_LEFT:
        case LAYOUT_FORCE_RIGHT:
        case LAYOUT_SPECIFIC:
        case LAYOUT_SYNC:
            break;
        case LAYOUT_MOVE_SELECTION:
        default:
            // Remember the previously selected view
            index = mSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                oldSel = getChildAt(index);
            }

            // Remember the previous first child
            oldFirst = getChildAt(0);

            if (mNextSelectedPosition >= 0) {
                delta = mNextSelectedPosition - mSelectedPosition;
            }

            // Caution: newSel might be null
            newSel = getChildAt(index + delta);
        }

        boolean dataChanged = mDataChanged;
        if (dataChanged) {
            handleDataChanged();
        }

        // Handle the empty set by removing all views that are visible
        // and calling it a day
        if (mItemCount == 0) {
            resetList();
            invokeOnItemScrollListener();
            return;
        } else if (mItemCount != mAdapter.getCount()) {
            throw new IllegalStateException("The content of the adapter has changed but "
                    + "ListView did not receive a notification. Make sure the content of "
                    + "your adapter is not modified from a background thread, but only "
                    + "from the UI thread. [in ListView(" + getId() + ", " + getClass() + ") with Adapter("
                    + mAdapter.getClass() + ")]");
        }

        setSelectedPositionInt(mNextSelectedPosition);

        // Pull all children into the RecycleBin.
        // These views will be reused if possible
        final int firstPosition = mFirstPosition;
        final RecycleBin recycleBin = mRecycler;

        // reset the focus restoration
        View focusLayoutRestoreDirectChild = null;

        // Don't put header or footer views into the Recycler. Those are
        // already cached in mHeaderViews;
        if (dataChanged) {
            for (int i = 0; i < childCount; i++) {
                recycleBin.addScrapView(getChildAt(i), firstPosition + i);
            }
        } else {
            recycleBin.fillActiveViews(childCount, firstPosition);
        }

        // take focus back to us temporarily to avoid the eventual
        // call to clear focus when removing the focused child below
        // from messing things up when ViewAncestor assigns focus back
        // to someone else
        final View focusedChild = getFocusedChild();
        if (focusedChild != null) {
            // TODO: in some cases focusedChild.getParent() == null

            // we can remember the focused view to restore after relayout if the
            // data hasn't changed, or if the focused position is a header or footer
            if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
                focusLayoutRestoreDirectChild = focusedChild;
                // remember the specific view that had focus
                focusLayoutRestoreView = findFocus();
                if (focusLayoutRestoreView != null) {
                    // tell it we are going to mess with it
                    focusLayoutRestoreView.onStartTemporaryDetach();
                }
            }
            requestFocus();
        }

        /*
         * // Remember which child, if any, had accessibility focus. final ViewRootImpl viewRootImpl = getViewRootImpl(); if (
         * viewRootImpl != null ) { final View accessFocusedView = viewRootImpl.getAccessibilityFocusedHost(); if (
         * accessFocusedView != null ) { final View accessFocusedChild = findAccessibilityFocusedChild( accessFocusedView ); if (
         * accessFocusedChild != null ) { if ( !dataChanged || isDirectChildHeaderOrFooter( accessFocusedChild ) ) { // If the
         * views won't be changing, try to maintain // focus on the current view host and (if // applicable) its virtual view.
         * accessibilityFocusLayoutRestoreView = accessFocusedView; accessibilityFocusLayoutRestoreNode = viewRootImpl
         * .getAccessibilityFocusedVirtualView(); } else { // Otherwise, try to maintain focus at the same // position.
         * accessibilityFocusPosition = getPositionForView( accessFocusedChild ); } } } }
         */

        // Clear out old views
        detachAllViewsFromParent();
        recycleBin.removeSkippedScrap();

        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            if (newSel != null) {
                sel = fillFromSelection(newSel.getLeft(), childrenLeft, childrenRight);
            } else {
                sel = fillFromMiddle(childrenLeft, childrenRight);
            }
            break;
        case LAYOUT_SYNC:
            sel = fillSpecific(mSyncPosition, mSpecificLeft);
            break;
        case LAYOUT_FORCE_RIGHT:
            sel = fillLeft(mItemCount - 1, childrenRight);
            adjustViewsLeftOrRight();
            break;
        case LAYOUT_FORCE_LEFT:
            mFirstPosition = 0;
            sel = fillFromLeft(childrenLeft);
            adjustViewsLeftOrRight();
            break;
        case LAYOUT_SPECIFIC:
            sel = fillSpecific(reconcileSelectedPosition(), mSpecificLeft);
            break;
        case LAYOUT_MOVE_SELECTION:
            sel = moveSelection(oldSel, newSel, delta, childrenLeft, childrenRight);
            break;
        default:
            if (childCount == 0) {
                if (!mStackFromRight) {
                    final int position = lookForSelectablePosition(0, true);
                    setSelectedPositionInt(position);
                    sel = fillFromLeft(childrenLeft);
                } else {
                    final int position = lookForSelectablePosition(mItemCount - 1, false);
                    setSelectedPositionInt(position);
                    sel = fillLeft(mItemCount - 1, childrenRight);
                }
            } else {
                if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
                    sel = fillSpecific(mSelectedPosition, oldSel == null ? childrenLeft : oldSel.getLeft());
                } else if (mFirstPosition < mItemCount) {
                    sel = fillSpecific(mFirstPosition, oldFirst == null ? childrenLeft : oldFirst.getLeft());
                } else {
                    sel = fillSpecific(0, childrenLeft);
                }
            }
            break;
        }

        // Flush any cached views that did not get reused above
        recycleBin.scrapActiveViews();

        if (sel != null) {
            // the current selected item should get focus if items
            // are focusable
            if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
                final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild
                        && focusLayoutRestoreView != null && focusLayoutRestoreView.requestFocus())
                        || sel.requestFocus();
                if (!focusWasTaken) {
                    // selected item didn't take focus, fine, but still want
                    // to make sure something else outside of the selected view
                    // has focus
                    final View focused = getFocusedChild();
                    if (focused != null) {
                        focused.clearFocus();
                    }
                    positionSelector(INVALID_POSITION, sel);
                } else {
                    sel.setSelected(false);
                    mSelectorRect.setEmpty();
                }
            } else {
                positionSelector(INVALID_POSITION, sel);
            }
            mSelectedLeft = sel.getLeft();
        } else {
            if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
                View child = getChildAt(mMotionPosition - mFirstPosition);
                if (child != null)
                    positionSelector(mMotionPosition, child);
            } else {
                mSelectedLeft = 0;
                mSelectorRect.setEmpty();
            }

            // even if there is not selected position, we may need to restore
            // focus (i.e. something focusable in touch mode)
            if (hasFocus() && focusLayoutRestoreView != null) {
                focusLayoutRestoreView.requestFocus();
            }
        }

        // Attempt to restore accessibility focus.
        // if ( accessibilityFocusLayoutRestoreNode != null ) {
        // accessibilityFocusLayoutRestoreNode.performAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS );
        // } else if ( accessibilityFocusLayoutRestoreView != null ) {
        // this method is marked as hidden. Shame on you google!
        // accessibilityFocusLayoutRestoreView.requestAccessibilityFocus();
        // } else if ( accessibilityFocusPosition != INVALID_POSITION ) {
        // Bound the position within the visible children.
        // final int position = MathUtils.constrain( ( accessibilityFocusPosition - mFirstPosition ), 0, ( getChildCount() - 1 ) );
        // final View restoreView = getChildAt( position );
        // if ( restoreView != null ) {
        // this method is marked as hidden. Shame on you google!
        // restoreView.requestAccessibilityFocus();
        // }
        // }

        // tell focus view we are done mucking with it, if it is still in
        // our view hierarchy.
        if (focusLayoutRestoreView != null && focusLayoutRestoreView.getWindowToken() != null) {
            focusLayoutRestoreView.onFinishTemporaryDetach();
        }

        mLayoutMode = LAYOUT_NORMAL;
        mDataChanged = false;
        if (mPositionScrollAfterLayout != null) {
            post(mPositionScrollAfterLayout);
            mPositionScrollAfterLayout = null;
        }
        mNeedSync = false;
        setNextSelectedPositionInt(mSelectedPosition);

        updateScrollIndicators();

        if (mItemCount > 0) {
            checkSelectionChanged();
        }

        invokeOnItemScrollListener();
    } finally {
        if (!blockLayoutRequests) {
            mBlockLayoutRequests = false;
        }
    }
}

From source file:com.awrtechnologies.carbudgetsales.hlistview.widget.HListView.java

@Override
protected void layoutChildren() {
    final boolean blockLayoutRequests = mBlockLayoutRequests;
    if (!blockLayoutRequests) {
        mBlockLayoutRequests = true;//from   ww w . java2  s  . com
    } else {
        return;
    }

    try {
        super.layoutChildren();

        invalidate();

        if (mAdapter == null) {
            resetList();
            invokeOnItemScrollListener();
            return;
        }

        int childrenLeft = mListPadding.left;
        int childrenRight = getRight() - getLeft() - mListPadding.right;

        int childCount = getChildCount();
        int index = 0;
        int delta = 0;

        View sel;
        View oldSel = null;
        View oldFirst = null;
        View newSel = null;

        View focusLayoutRestoreView = null;

        // AccessibilityNodeInfo accessibilityFocusLayoutRestoreNode = null;
        // View accessibilityFocusLayoutRestoreView = null;
        // int accessibilityFocusPosition = INVALID_POSITION;

        // Remember stuff we will need down below
        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            index = mNextSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                newSel = getChildAt(index);
            }
            break;
        case LAYOUT_FORCE_LEFT:
        case LAYOUT_FORCE_RIGHT:
        case LAYOUT_SPECIFIC:
        case LAYOUT_SYNC:
            break;
        case LAYOUT_MOVE_SELECTION:
        default:
            // Remember the previously selected view
            index = mSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                oldSel = getChildAt(index);
            }

            // Remember the previous first child
            oldFirst = getChildAt(0);

            if (mNextSelectedPosition >= 0) {
                delta = mNextSelectedPosition - mSelectedPosition;
            }

            // Caution: newSel might be null
            newSel = getChildAt(index + delta);
        }

        boolean dataChanged = mDataChanged;
        if (dataChanged) {
            handleDataChanged();
        }

        // Handle the empty set by removing all views that are visible
        // and calling it a day
        if (mItemCount == 0) {
            resetList();
            invokeOnItemScrollListener();
            return;
        } else if (mItemCount != mAdapter.getCount()) {
            throw new IllegalStateException(
                    "The content of the com.awrtechnologies.carbudgetsales.adapter has changed but "
                            + "ListView did not receive a notification. Make sure the content of "
                            + "your com.awrtechnologies.carbudgetsales.adapter is not modified from a background thread, but only "
                            + "from the UI thread. [in ListView(" + getId() + ", " + getClass()
                            + ") with Adapter(" + mAdapter.getClass() + ")]");
        }

        setSelectedPositionInt(mNextSelectedPosition);

        // Pull all children into the RecycleBin.
        // These views will be reused if possible
        final int firstPosition = mFirstPosition;
        final RecycleBin recycleBin = mRecycler;

        // reset the focus restoration
        View focusLayoutRestoreDirectChild = null;

        // Don't put header or footer views into the Recycler. Those are
        // already cached in mHeaderViews;
        if (dataChanged) {
            for (int i = 0; i < childCount; i++) {
                recycleBin.addScrapView(getChildAt(i), firstPosition + i);
            }
        } else {
            recycleBin.fillActiveViews(childCount, firstPosition);
        }

        // take focus back to us temporarily to avoid the eventual
        // call to clear focus when removing the focused child below
        // from messing things up when ViewAncestor assigns focus back
        // to someone else
        final View focusedChild = getFocusedChild();
        if (focusedChild != null) {
            // TODO: in some cases focusedChild.getParent() == null

            // we can remember the focused view to restore after relayout if the
            // com.awrtechnologies.carbudgetsales.data hasn't changed, or if the focused position is a header or footer
            if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
                focusLayoutRestoreDirectChild = focusedChild;
                // remember the specific view that had focus
                focusLayoutRestoreView = findFocus();
                if (focusLayoutRestoreView != null) {
                    // tell it we are going to mess with it
                    focusLayoutRestoreView.onStartTemporaryDetach();
                }
            }
            requestFocus();
        }

        /*
         * // Remember which child, if any, had accessibility focus. final ViewRootImpl viewRootImpl = getViewRootImpl(); if (
         * viewRootImpl != null ) { final View accessFocusedView = viewRootImpl.getAccessibilityFocusedHost(); if (
         * accessFocusedView != null ) { final View accessFocusedChild = findAccessibilityFocusedChild( accessFocusedView ); if (
         * accessFocusedChild != null ) { if ( !dataChanged || isDirectChildHeaderOrFooter( accessFocusedChild ) ) { // If the
         * views won't be changing, try to maintain // focus on the current view host and (if // applicable) its virtual view.
         * accessibilityFocusLayoutRestoreView = accessFocusedView; accessibilityFocusLayoutRestoreNode = viewRootImpl
         * .getAccessibilityFocusedVirtualView(); } else { // Otherwise, try to maintain focus at the same // position.
         * accessibilityFocusPosition = getPositionForView( accessFocusedChild ); } } } }
         */

        // Clear out old views
        detachAllViewsFromParent();
        recycleBin.removeSkippedScrap();

        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            if (newSel != null) {
                sel = fillFromSelection(newSel.getLeft(), childrenLeft, childrenRight);
            } else {
                sel = fillFromMiddle(childrenLeft, childrenRight);
            }
            break;
        case LAYOUT_SYNC:
            sel = fillSpecific(mSyncPosition, mSpecificLeft);
            break;
        case LAYOUT_FORCE_RIGHT:
            sel = fillLeft(mItemCount - 1, childrenRight);
            adjustViewsLeftOrRight();
            break;
        case LAYOUT_FORCE_LEFT:
            mFirstPosition = 0;
            sel = fillFromLeft(childrenLeft);
            adjustViewsLeftOrRight();
            break;
        case LAYOUT_SPECIFIC:
            sel = fillSpecific(reconcileSelectedPosition(), mSpecificLeft);
            break;
        case LAYOUT_MOVE_SELECTION:
            sel = moveSelection(oldSel, newSel, delta, childrenLeft, childrenRight);
            break;
        default:
            if (childCount == 0) {
                if (!mStackFromRight) {
                    final int position = lookForSelectablePosition(0, true);
                    setSelectedPositionInt(position);
                    sel = fillFromLeft(childrenLeft);
                } else {
                    final int position = lookForSelectablePosition(mItemCount - 1, false);
                    setSelectedPositionInt(position);
                    sel = fillLeft(mItemCount - 1, childrenRight);
                }
            } else {
                if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
                    sel = fillSpecific(mSelectedPosition, oldSel == null ? childrenLeft : oldSel.getLeft());
                } else if (mFirstPosition < mItemCount) {
                    sel = fillSpecific(mFirstPosition, oldFirst == null ? childrenLeft : oldFirst.getLeft());
                } else {
                    sel = fillSpecific(0, childrenLeft);
                }
            }
            break;
        }

        // Flush any cached views that did not get reused above
        recycleBin.scrapActiveViews();

        if (sel != null) {
            // the current selected item should get focus if items
            // are focusable
            if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
                final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild
                        && focusLayoutRestoreView != null && focusLayoutRestoreView.requestFocus())
                        || sel.requestFocus();
                if (!focusWasTaken) {
                    // selected item didn't take focus, fine, but still want
                    // to make sure something else outside of the selected view
                    // has focus
                    final View focused = getFocusedChild();
                    if (focused != null) {
                        focused.clearFocus();
                    }
                    positionSelector(INVALID_POSITION, sel);
                } else {
                    sel.setSelected(false);
                    mSelectorRect.setEmpty();
                }
            } else {
                positionSelector(INVALID_POSITION, sel);
            }
            mSelectedLeft = sel.getLeft();
        } else {
            if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
                View child = getChildAt(mMotionPosition - mFirstPosition);
                if (child != null)
                    positionSelector(mMotionPosition, child);
            } else {
                mSelectedLeft = 0;
                mSelectorRect.setEmpty();
            }

            // even if there is not selected position, we may need to restore
            // focus (i.e. something focusable in touch mode)
            if (hasFocus() && focusLayoutRestoreView != null) {
                focusLayoutRestoreView.requestFocus();
            }
        }

        // Attempt to restore accessibility focus.
        // if ( accessibilityFocusLayoutRestoreNode != null ) {
        // accessibilityFocusLayoutRestoreNode.performAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS );
        // } else if ( accessibilityFocusLayoutRestoreView != null ) {
        // this method is marked as hidden. Shame on you google!
        // accessibilityFocusLayoutRestoreView.requestAccessibilityFocus();
        // } else if ( accessibilityFocusPosition != INVALID_POSITION ) {
        // Bound the position within the visible children.
        // final int position = MathUtils.constrain( ( accessibilityFocusPosition - mFirstPosition ), 0, ( getChildCount() - 1 ) );
        // final View restoreView = getChildAt( position );
        // if ( restoreView != null ) {
        // this method is marked as hidden. Shame on you google!
        // restoreView.requestAccessibilityFocus();
        // }
        // }

        // tell focus view we are done mucking with it, if it is still in
        // our view hierarchy.
        if (focusLayoutRestoreView != null && focusLayoutRestoreView.getWindowToken() != null) {
            focusLayoutRestoreView.onFinishTemporaryDetach();
        }

        mLayoutMode = LAYOUT_NORMAL;
        mDataChanged = false;
        if (mPositionScrollAfterLayout != null) {
            post(mPositionScrollAfterLayout);
            mPositionScrollAfterLayout = null;
        }
        mNeedSync = false;
        setNextSelectedPositionInt(mSelectedPosition);

        updateScrollIndicators();

        if (mItemCount > 0) {
            checkSelectionChanged();
        }

        invokeOnItemScrollListener();
    } finally {
        if (!blockLayoutRequests) {
            mBlockLayoutRequests = false;
        }
    }
}

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

@Override
protected void layoutChildren() {
    final boolean blockLayoutRequests = mBlockLayoutRequests;
    if (!blockLayoutRequests) {
        mBlockLayoutRequests = true;//from ww  w .  j a va  2  s  .c  o  m
    } else {
        return;
    }

    try {
        super.layoutChildren();

        invalidate();

        if (mAdapter == null) {
            resetList();
            invokeOnItemScrollListener();
            return;
        }

        int childrenLeft = mListPadding.left;
        int childrenRight = getRight() - getLeft() - mListPadding.right;

        int childCount = getChildCount();
        int index = 0;
        int delta = 0;

        View sel;
        View oldSel = null;
        View oldFirst = null;
        View newSel = null;

        View focusLayoutRestoreView = null;

        AccessibilityNodeInfo accessibilityFocusLayoutRestoreNode = null;
        View accessibilityFocusLayoutRestoreView = null;
        int accessibilityFocusPosition = INVALID_POSITION;

        // Remember stuff we will need down below
        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            index = mNextSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                newSel = getChildAt(index);
            }
            break;
        case LAYOUT_FORCE_LEFT:
        case LAYOUT_FORCE_RIGHT:
        case LAYOUT_SPECIFIC:
        case LAYOUT_SYNC:
            break;
        case LAYOUT_MOVE_SELECTION:
        default:
            // Remember the previously selected view
            index = mSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                oldSel = getChildAt(index);
            }

            // Remember the previous first child
            oldFirst = getChildAt(0);

            if (mNextSelectedPosition >= 0) {
                delta = mNextSelectedPosition - mSelectedPosition;
            }

            // Caution: newSel might be null
            newSel = getChildAt(index + delta);
        }

        boolean dataChanged = mDataChanged;
        if (dataChanged) {
            handleDataChanged();
        }

        // Handle the empty set by removing all views that are visible
        // and calling it a day
        if (mItemCount == 0) {
            resetList();
            invokeOnItemScrollListener();
            return;
        } else if (mItemCount != mAdapter.getCount()) {
            throw new IllegalStateException("The content of the adapter has changed but "
                    + "ListView did not receive a notification. Make sure the content of "
                    + "your adapter is not modified from a background thread, but only "
                    + "from the UI thread. [in ListView(" + getId() + ", " + getClass() + ") with Adapter("
                    + mAdapter.getClass() + ")]");
        }

        setSelectedPositionInt(mNextSelectedPosition);

        // Pull all children into the RecycleBin.
        // These views will be reused if possible
        final int firstPosition = mFirstPosition;
        final RecycleBin recycleBin = mRecycler;

        // reset the focus restoration
        View focusLayoutRestoreDirectChild = null;

        // Don't put header or footer views into the Recycler. Those are
        // already cached in mHeaderViews;
        if (dataChanged) {
            for (int i = 0; i < childCount; i++) {
                recycleBin.addScrapView(getChildAt(i), firstPosition + i);
            }
        } else {
            recycleBin.fillActiveViews(childCount, firstPosition);
        }

        // take focus back to us temporarily to avoid the eventual
        // call to clear focus when removing the focused child below
        // from messing things up when ViewAncestor assigns focus back
        // to someone else
        final View focusedChild = getFocusedChild();
        if (focusedChild != null) {
            // TODO: in some cases focusedChild.getParent() == null

            // we can remember the focused view to restore after relayout if the
            // data hasn't changed, or if the focused position is a header or footer
            if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
                focusLayoutRestoreDirectChild = focusedChild;
                // remember the specific view that had focus
                focusLayoutRestoreView = findFocus();
                if (focusLayoutRestoreView != null) {
                    // tell it we are going to mess with it
                    focusLayoutRestoreView.onStartTemporaryDetach();
                }
            }
            requestFocus();
        }

        // TODO We can use those accessability methods, we just remove those (j.m.)
        //            //Remember which child, if any, had accessibility focus.
        //            final ViewRootImpl viewRootImpl = getViewRootImpl();
        //            if (viewRootImpl != null) {
        //                final View accessFocusedView = viewRootImpl.getAccessibilityFocusedHost();
        //                if (accessFocusedView != null) {
        //                    final View accessFocusedChild = findAccessibilityFocusedChild(
        //                            accessFocusedView);
        //                    if (accessFocusedChild != null) {
        //                        if (!dataChanged || isDirectChildHeaderOrFooter(accessFocusedChild)) {
        //                            // If the views won't be changing, try to maintain
        //                            // focus on the current view host and (if
        //                            // applicable) its virtual view.
        //                            accessibilityFocusLayoutRestoreView = accessFocusedView;
        //                            accessibilityFocusLayoutRestoreNode = viewRootImpl
        //                                    .getAccessibilityFocusedVirtualView();
        //                        } else {
        //                            // Otherwise, try to maintain focus at the same
        //                            // position.
        //                            accessibilityFocusPosition = getPositionForView(accessFocusedChild);
        //                        }
        //                    }
        //                }
        //            }

        // Clear out old views
        detachAllViewsFromParent();
        recycleBin.removeSkippedScrap();

        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            if (newSel != null) {
                sel = fillFromSelection(newSel.getLeft(), childrenLeft, childrenRight);
            } else {
                sel = fillFromMiddle(childrenLeft, childrenRight);
            }
            break;
        case LAYOUT_SYNC:
            sel = fillSpecific(mSyncPosition, mSpecificLeft);
            break;
        case LAYOUT_FORCE_RIGHT:
            sel = fillLeft(mItemCount - 1, childrenRight);
            adjustViewsLeftOrRight();
            break;
        case LAYOUT_FORCE_LEFT:
            mFirstPosition = 0;
            sel = fillFromLeft(childrenLeft);
            adjustViewsLeftOrRight();
            break;
        case LAYOUT_SPECIFIC:
            sel = fillSpecific(reconcileSelectedPosition(), mSpecificLeft);
            break;
        case LAYOUT_MOVE_SELECTION:
            sel = moveSelection(oldSel, newSel, delta, childrenLeft, childrenRight);
            break;
        default:
            if (childCount == 0) {
                if (!mStackFromRight) {
                    final int position = lookForSelectablePosition(0, true);
                    setSelectedPositionInt(position);
                    sel = fillFromLeft(childrenLeft);
                } else {
                    final int position = lookForSelectablePosition(mItemCount - 1, false);
                    setSelectedPositionInt(position);
                    sel = fillLeft(mItemCount - 1, childrenRight);
                }
            } else {
                if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
                    sel = fillSpecific(mSelectedPosition, oldSel == null ? childrenLeft : oldSel.getLeft());
                } else if (mFirstPosition < mItemCount) {
                    sel = fillSpecific(mFirstPosition, oldFirst == null ? childrenLeft : oldFirst.getLeft());
                } else {
                    sel = fillSpecific(0, childrenLeft);
                }
            }
            break;
        }

        // Flush any cached views that did not get reused above
        recycleBin.scrapActiveViews();

        if (sel != null) {
            // the current selected item should get focus if items
            // are focusable
            if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
                final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild
                        && focusLayoutRestoreView != null && focusLayoutRestoreView.requestFocus())
                        || sel.requestFocus();
                if (!focusWasTaken) {
                    // selected item didn't take focus, fine, but still want
                    // to make sure something else outside of the selected view
                    // has focus
                    final View focused = getFocusedChild();
                    if (focused != null) {
                        focused.clearFocus();
                    }
                    positionSelector(INVALID_POSITION, sel);
                } else {
                    sel.setSelected(false);
                    mSelectorRect.setEmpty();
                }
            } else {
                positionSelector(INVALID_POSITION, sel);
            }
            mSelectedLeft = sel.getLeft();
        } else {
            if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
                View child = getChildAt(mMotionPosition - mFirstPosition);
                if (child != null)
                    positionSelector(mMotionPosition, child);
            } else {
                mSelectedLeft = 0;
                mSelectorRect.setEmpty();
            }

            // even if there is not selected position, we may need to restore
            // focus (i.e. something focusable in touch mode)
            if (hasFocus() && focusLayoutRestoreView != null) {
                focusLayoutRestoreView.requestFocus();
            }
        }
        // TODO We can use those accessability methods, we just remove those (j.m.)
        //            // Attempt to restore accessibility focus.
        //            if (accessibilityFocusLayoutRestoreNode != null) {
        //                accessibilityFocusLayoutRestoreNode.performAction(
        //                        AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
        //            } else if (accessibilityFocusLayoutRestoreView != null) {
        //                accessibilityFocusLayoutRestoreView.requestAccessibilityFocus();
        //            } else if (accessibilityFocusPosition != INVALID_POSITION) {
        //                // Bound the position within the visible children.
        //                final int position = MathUtils.constrain(
        //                        (accessibilityFocusPosition - mFirstPosition), 0, (getChildCount() - 1));
        //                final View restoreView = getChildAt(position);
        //                if (restoreView != null) {
        //                    restoreView.requestAccessibilityFocus();
        //                }
        //            }

        // tell focus view we are done mucking with it, if it is still in
        // our view hierarchy.
        if (focusLayoutRestoreView != null && focusLayoutRestoreView.getWindowToken() != null) {
            focusLayoutRestoreView.onFinishTemporaryDetach();
        }

        mLayoutMode = LAYOUT_NORMAL;
        mDataChanged = false;
        if (mPositionScrollAfterLayout != null) {
            post(mPositionScrollAfterLayout);
            mPositionScrollAfterLayout = null;
        }
        mNeedSync = false;
        setNextSelectedPositionInt(mSelectedPosition);

        updateScrollIndicators();

        if (mItemCount > 0) {
            checkSelectionChanged();
        }

        invokeOnItemScrollListener();
    } finally {
        if (!blockLayoutRequests) {
            mBlockLayoutRequests = false;
        }
    }
}

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

@Override
protected void layoutChildren() {
    final boolean blockLayoutRequests = mBlockLayoutRequests;
    if (!blockLayoutRequests) {
        mBlockLayoutRequests = true;/*from  www.j  a v a 2  s .com*/
    } else {
        return;
    }

    try {
        super.layoutChildren();

        invalidate();

        if (mAdapter == null) {
            resetList();
            invokeOnItemScrollListener();
            return;
        }

        int childrenTop = mListPadding.top;
        int childrenBottom = getBottom() - getTop() - mListPadding.bottom;

        int childCount = getChildCount();
        int index = 0;
        int delta = 0;

        View sel;
        View oldSel = null;
        View oldFirst = null;
        View newSel = null;

        View focusLayoutRestoreView = null;

        AccessibilityNodeInfo accessibilityFocusLayoutRestoreNode = null;
        View accessibilityFocusLayoutRestoreView = null;
        int accessibilityFocusPosition = INVALID_POSITION;

        // Remember stuff we will need down below
        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            index = mNextSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                newSel = getChildAt(index);
            }
            break;
        case LAYOUT_FORCE_TOP:
        case LAYOUT_FORCE_BOTTOM:
        case LAYOUT_SPECIFIC:
        case LAYOUT_SYNC:
            break;
        case LAYOUT_MOVE_SELECTION:
        default:
            // Remember the previously selected view
            index = mSelectedPosition - mFirstPosition;
            if (index >= 0 && index < childCount) {
                oldSel = getChildAt(index);
            }

            // Remember the previous first child
            oldFirst = getChildAt(0);

            if (mNextSelectedPosition >= 0) {
                delta = mNextSelectedPosition - mSelectedPosition;
            }

            // Caution: newSel might be null
            newSel = getChildAt(index + delta);
        }

        boolean dataChanged = mDataChanged;
        if (dataChanged) {
            handleDataChanged();
        }

        // Handle the empty set by removing all views that are visible
        // and calling it a day
        if (mItemCount == 0) {
            resetList();
            invokeOnItemScrollListener();
            return;
        } else if (mItemCount != mAdapter.getCount()) {
            throw new IllegalStateException("The content of the adapter has changed but "
                    + "ListView did not receive a notification. Make sure the content of "
                    + "your adapter is not modified from a background thread, but only "
                    + "from the UI thread. [in ListView(" + getId() + ", " + getClass() + ") with Adapter("
                    + mAdapter.getClass() + ")]");
        }

        setSelectedPositionInt(mNextSelectedPosition);

        // Pull all children into the RecycleBin.
        // These views will be reused if possible
        final int firstPosition = mFirstPosition;
        final RecycleBin recycleBin = mRecycler;

        // reset the focus restoration
        View focusLayoutRestoreDirectChild = null;

        // Don't put header or footer views into the Recycler. Those are
        // already cached in mHeaderViews;
        if (dataChanged) {
            for (int i = 0; i < childCount; i++) {
                recycleBin.addScrapView(getChildAt(i), firstPosition + i);
            }
        } else {
            recycleBin.fillActiveViews(childCount, firstPosition);
        }

        // take focus back to us temporarily to avoid the eventual
        // call to clear focus when removing the focused child below
        // from messing things up when ViewAncestor assigns focus back
        // to someone else
        final View focusedChild = getFocusedChild();
        if (focusedChild != null) {
            // TODO: in some cases focusedChild.getParent() == null

            // we can remember the focused view to restore after relayout if the
            // data hasn't changed, or if the focused position is a header or footer
            if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
                focusLayoutRestoreDirectChild = focusedChild;
                // remember the specific view that had focus
                focusLayoutRestoreView = findFocus();
                if (focusLayoutRestoreView != null) {
                    // tell it we are going to mess with it
                    focusLayoutRestoreView.onStartTemporaryDetach();
                }
            }
            requestFocus();
        }

        // TODO We can use those accessability methods, we just remove those (j.m.)
        //            //Remember which child, if any, had accessibility focus.
        //            final ViewRootImpl viewRootImpl = getViewRootImpl();
        //            if (viewRootImpl != null) {
        //                final View accessFocusedView = viewRootImpl.getAccessibilityFocusedHost();
        //                if (accessFocusedView != null) {
        //                    final View accessFocusedChild = findAccessibilityFocusedChild(
        //                            accessFocusedView);
        //                    if (accessFocusedChild != null) {
        //                        if (!dataChanged || isDirectChildHeaderOrFooter(accessFocusedChild)) {
        //                            // If the views won't be changing, try to maintain
        //                            // focus on the current view host and (if
        //                            // applicable) its virtual view.
        //                            accessibilityFocusLayoutRestoreView = accessFocusedView;
        //                            accessibilityFocusLayoutRestoreNode = viewRootImpl
        //                                    .getAccessibilityFocusedVirtualView();
        //                        } else {
        //                            // Otherwise, try to maintain focus at the same
        //                            // position.
        //                            accessibilityFocusPosition = getPositionForView(accessFocusedChild);
        //                        }
        //                    }
        //                }
        //            }

        // Clear out old views
        detachAllViewsFromParent();
        recycleBin.removeSkippedScrap();

        switch (mLayoutMode) {
        case LAYOUT_SET_SELECTION:
            if (newSel != null) {
                sel = fillFromSelection(newSel.getTop(), childrenTop, childrenBottom);
            } else {
                sel = fillFromMiddle(childrenTop, childrenBottom);
            }
            break;
        case LAYOUT_SYNC:
            sel = fillSpecific(mSyncPosition, mSpecificTop);
            break;
        case LAYOUT_FORCE_BOTTOM:
            sel = fillUp(mItemCount - 1, childrenBottom);
            adjustViewsUpOrDown();
            break;
        case LAYOUT_FORCE_TOP:
            mFirstPosition = 0;
            sel = fillFromTop(childrenTop);
            adjustViewsUpOrDown();
            break;
        case LAYOUT_SPECIFIC:
            sel = fillSpecific(reconcileSelectedPosition(), mSpecificTop);
            break;
        case LAYOUT_MOVE_SELECTION:
            sel = moveSelection(oldSel, newSel, delta, childrenTop, childrenBottom);
            break;
        default:
            if (childCount == 0) {
                if (!mStackFromBottom) {
                    final int position = lookForSelectablePosition(0, true);
                    setSelectedPositionInt(position);
                    sel = fillFromTop(childrenTop);
                } else {
                    final int position = lookForSelectablePosition(mItemCount - 1, false);
                    setSelectedPositionInt(position);
                    sel = fillUp(mItemCount - 1, childrenBottom);
                }
            } else {
                if (mSelectedPosition >= 0 && mSelectedPosition < mItemCount) {
                    sel = fillSpecific(mSelectedPosition, oldSel == null ? childrenTop : oldSel.getTop());
                } else if (mFirstPosition < mItemCount) {
                    sel = fillSpecific(mFirstPosition, oldFirst == null ? childrenTop : oldFirst.getTop());
                } else {
                    sel = fillSpecific(0, childrenTop);
                }
            }
            break;
        }

        // Flush any cached views that did not get reused above
        recycleBin.scrapActiveViews();

        if (sel != null) {
            // the current selected item should get focus if items
            // are focusable
            if (mItemsCanFocus && hasFocus() && !sel.hasFocus()) {
                final boolean focusWasTaken = (sel == focusLayoutRestoreDirectChild
                        && focusLayoutRestoreView != null && focusLayoutRestoreView.requestFocus())
                        || sel.requestFocus();
                if (!focusWasTaken) {
                    // selected item didn't take focus, fine, but still want
                    // to make sure something else outside of the selected view
                    // has focus
                    final View focused = getFocusedChild();
                    if (focused != null) {
                        focused.clearFocus();
                    }
                    positionSelector(INVALID_POSITION, sel);
                } else {
                    sel.setSelected(false);
                    mSelectorRect.setEmpty();
                }
            } else {
                positionSelector(INVALID_POSITION, sel);
            }
            mSelectedTop = sel.getTop();
        } else {
            if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
                View child = getChildAt(mMotionPosition - mFirstPosition);
                if (child != null)
                    positionSelector(mMotionPosition, child);
            } else {
                mSelectedTop = 0;
                mSelectorRect.setEmpty();
            }

            // even if there is not selected position, we may need to restore
            // focus (i.e. something focusable in touch mode)
            if (hasFocus() && focusLayoutRestoreView != null) {
                focusLayoutRestoreView.requestFocus();
            }
        }
        // TODO We can use those accessability methods, we just remove those (j.m.)
        //            // Attempt to restore accessibility focus.
        //            if (accessibilityFocusLayoutRestoreNode != null) {
        //                accessibilityFocusLayoutRestoreNode.performAction(
        //                        AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
        //            } else if (accessibilityFocusLayoutRestoreView != null) {
        //                accessibilityFocusLayoutRestoreView.requestAccessibilityFocus();
        //            } else if (accessibilityFocusPosition != INVALID_POSITION) {
        //                // Bound the position within the visible children.
        //                final int position = MathUtils.constrain(
        //                        (accessibilityFocusPosition - mFirstPosition), 0, (getChildCount() - 1));
        //                final View restoreView = getChildAt(position);
        //                if (restoreView != null) {
        //                    restoreView.requestAccessibilityFocus();
        //                }
        //            }

        // tell focus view we are done mucking with it, if it is still in
        // our view hierarchy.
        if (focusLayoutRestoreView != null && focusLayoutRestoreView.getWindowToken() != null) {
            focusLayoutRestoreView.onFinishTemporaryDetach();
        }

        mLayoutMode = LAYOUT_NORMAL;
        mDataChanged = false;
        if (mPositionScrollAfterLayout != null) {
            post(mPositionScrollAfterLayout);
            mPositionScrollAfterLayout = null;
        }
        mNeedSync = false;
        setNextSelectedPositionInt(mSelectedPosition);

        updateScrollIndicators();

        if (mItemCount > 0) {
            checkSelectionChanged();
        }

        invokeOnItemScrollListener();
    } finally {
        if (!blockLayoutRequests) {
            mBlockLayoutRequests = false;
        }
    }
}