Example usage for android.view View getLayoutParams

List of usage examples for android.view View getLayoutParams

Introduction

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

Prototype

@ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
public ViewGroup.LayoutParams getLayoutParams() 

Source Link

Document

Get the LayoutParams associated with this view.

Usage

From source file:app.umitems.greenclock.widget.sgv.StaggeredGridView.java

/**
 * Important: this method will leave offscreen views attached if they
 * are required to maintain the invariant that child view with index i
 * is always the view corresponding to position mFirstPosition + i.
 *//*from  w  ww  .ja  va  2 s. co  m*/
private void recycleOffscreenViews() {
    if (getChildCount() == 0) {
        return;
    }

    final int height = getHeight();
    final int clearAbove = -mItemMargin;
    final int clearBelow = height + mItemMargin;
    for (int i = getChildCount() - 1; i >= 0; i--) {
        final View child = getChildAt(i);
        if (child.getTop() <= clearBelow) {
            // There may be other offscreen views, but we need to maintain
            // the invariant documented above.
            break;
        }

        child.clearFocus();
        if (mInLayout) {
            removeViewsInLayout(i, 1);
        } else {
            removeViewAt(i);
        }

        mRecycler.addScrap(child);
    }

    while (getChildCount() > 0) {
        final View child = getChildAt(0);
        if (child.getBottom() >= clearAbove) {
            // There may be other offscreen views, but we need to maintain
            // the invariant documented above.
            break;
        }

        child.clearFocus();
        if (mInLayout) {
            removeViewsInLayout(0, 1);
        } else {
            removeViewAt(0);
        }

        mRecycler.addScrap(child);
        mFirstPosition++;
    }

    final int childCount = getChildCount();
    if (childCount > 0) {
        // Repair the top and bottom column boundaries from the views we still have
        Arrays.fill(mItemTops, Integer.MAX_VALUE);
        Arrays.fill(mItemBottoms, Integer.MIN_VALUE);
        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            final int top = child.getTop() - mItemMargin;
            final int bottom = child.getBottom();
            LayoutRecord rec = mLayoutRecords.get(mFirstPosition + i);

            // It's possible the layout record could be null for visible views because
            // they are cleared between adapter data set changes, but the views are left
            // attached for the purpose of animations. Hence, populate the layout record again.
            if (rec == null) {
                rec = recreateLayoutRecord(mFirstPosition + i, child, lp);
            }

            // In LTR layout, iterate across each column that this child is laid out in,
            // starting from the child's first column (lp.column).  For each column, update
            // mItemTops and mItemBottoms appropriately to take into account this child's
            // dimension.  In RTL layout, iterate in reverse, where the child's starting
            // column would start from the right-most.
            final int span = Math.min(mColCount, lp.span);
            for (int spanIndex = 0; spanIndex < span; spanIndex++) {
                final int col = mIsRtlLayout ? lp.column - spanIndex : lp.column + spanIndex;
                final int colTop = top - rec.getMarginAbove(spanIndex);
                final int colBottom = bottom + rec.getMarginBelow(spanIndex);
                if (colTop < mItemTops[col]) {
                    mItemTops[col] = colTop;
                }
                if (colBottom > mItemBottoms[col]) {
                    mItemBottoms[col] = colBottom;
                }
            }
        }

        for (int col = 0; col < mColCount; col++) {
            if (mItemTops[col] == Integer.MAX_VALUE) {
                // If one was untouched, both were.
                final int top = getPaddingTop();
                mItemTops[col] = top;
                mItemBottoms[col] = top;
            }
        }
    }

    mCurrentScrollState = getScrollState();
}

From source file:self.philbrown.droidQuery.$.java

/**
 * Adds an Image over each selected View as a mask.
 * In most cases, this mask can be retrieved by querying siblings. For example:
 * <pre>/*from   w  ww.ja va 2s  .  c om*/
 * ImageView mask = (ImageView) $.with(myView).parent().selectChildren().selectImages().view(0);
 * </pre>
 * @param source asset path, file path (starting with "file://") or URL to image
 * @param width specifies the output bitmap width
 * @param height specifies the output bitmap height
 * @param error if the given source is a file or asset, this receives a droidQuery wrapping the 
 * current context and the {@code Throwable} error. Otherwise, this will receive an
 * Ajax error.
 * @return this
 * @see AjaxOptions#error(Function)
 */
public $ mask(String source, int width, int height, Function error) {
    if (source.startsWith("file://")) {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inPreferredConfig = Bitmap.Config.ARGB_8888;
            if (width >= 0)
                opt.outWidth = width;
            if (height >= 0)
                opt.outHeight = height;
            Bitmap bitmap = BitmapFactory.decodeFile(source.substring(6), opt);
            for (View v : views) {
                ImageView image = new ImageView(context);
                image.setImageBitmap(Bitmap.createBitmap(bitmap));
                image.setScaleType(ScaleType.FIT_XY);
                ViewParent parent = v.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    image.setLayoutParams(v.getLayoutParams());
                    ((ViewGroup) parent).addView(image);
                } else if (v instanceof ViewGroup) {
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    ((ViewGroup) v).addView(image);
                }
            }
        } catch (Throwable t) {
            if (error != null) {
                error.invoke($.with(context), t);
            }
        }
    } else if (URLUtil.isValidUrl(source)) {
        AjaxOptions options = new AjaxOptions().url(source).type("GET").dataType("image").context(context)
                .global(false).success(new Function() {
                    @Override
                    public void invoke($ droidQuery, Object... params) {
                        Bitmap bitmap = (Bitmap) params[0];
                        for (View v : views) {
                            ImageView image = new ImageView(context);
                            image.setImageBitmap(Bitmap.createBitmap(bitmap));
                            image.setScaleType(ScaleType.FIT_XY);
                            ViewParent parent = v.getParent();
                            if (parent != null && parent instanceof ViewGroup) {
                                image.setLayoutParams(v.getLayoutParams());
                                ((ViewGroup) parent).addView(image);
                            } else if (v instanceof ViewGroup) {
                                image.setLayoutParams(
                                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                ViewGroup.LayoutParams.MATCH_PARENT));
                                ((ViewGroup) v).addView(image);
                            }
                        }
                    }
                });

        if (error != null) {
            options.error(error);
        }
        if (width >= 0) {
            options.imageWidth(width);
        }
        if (height >= 0) {
            options.imageHeight(height);
        }
        $.ajax(options);
    } else {
        try {
            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inSampleSize = 1;
            opt.inPurgeable = true;
            opt.inInputShareable = false;
            if (width >= 0)
                opt.outWidth = width;
            if (height >= 0)
                opt.outHeight = height;
            Bitmap bitmap = BitmapFactory.decodeStream(context.getAssets().open(source), new Rect(0, 0, 0, 0),
                    opt);
            for (View v : views) {
                ImageView image = new ImageView(context);
                image.setImageBitmap(Bitmap.createBitmap(bitmap));
                image.setScaleType(ScaleType.FIT_XY);
                ViewParent parent = v.getParent();
                if (parent != null && parent instanceof ViewGroup) {
                    image.setLayoutParams(v.getLayoutParams());
                    ((ViewGroup) parent).addView(image);
                } else if (v instanceof ViewGroup) {
                    image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
                    ((ViewGroup) v).addView(image);
                }
            }

        } catch (Throwable t) {
            if (error != null) {
                error.invoke($.with(context), t);
            }
        }

    }
    return this;
}

From source file:android.support.v7.widget.RecyclerView.java

void markItemDecorInsetsDirty() {
    final int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        final View child = getChildAt(i);
        ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
    }//  w  w  w .  j a va2  s  . c  om
}

From source file:android.support.v7.widget.RecyclerView.java

Rect getItemDecorInsetsForChild(View child) {
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    if (!lp.mInsetsDirty) {
        return lp.mDecorInsets;
    }/*ww w. jav a  2  s .c  o  m*/

    final Rect insets = lp.mDecorInsets;
    insets.set(0, 0, 0, 0);
    final int decorCount = mItemDecorations.size();
    for (int i = 0; i < decorCount; i++) {
        mTempRect.set(0, 0, 0, 0);
        mItemDecorations.get(i).getItemOffsets(mTempRect, lp.getViewPosition(), this);
        insets.left += mTempRect.left;
        insets.top += mTempRect.top;
        insets.right += mTempRect.right;
        insets.bottom += mTempRect.bottom;
    }
    lp.mInsetsDirty = false;
    return insets;
}

From source file:cc.flydev.launcher.Workspace.java

/**
 * Adds the specified child in the specified screen. The position and dimension of
 * the child are defined by x, y, spanX and spanY.
 *
 * @param child The child to add in one of the workspace's screens.
 * @param screenId The screen in which to add the child.
 * @param x The X position of the child in the screen's grid.
 * @param y The Y position of the child in the screen's grid.
 * @param spanX The number of cells spanned horizontally by the child.
 * @param spanY The number of cells spanned vertically by the child.
 * @param insert When true, the child is inserted at the beginning of the children list.
 * @param computeXYFromRank When true, we use the rank (stored in screenId) to compute
 *                          the x and y position in which to place hotseat items. Otherwise
 *                          we use the x and y position to compute the rank.
 *///www. ja v a 2s.c o  m
void addInScreen(View child, long container, long screenId, int x, int y, int spanX, int spanY, boolean insert,
        boolean computeXYFromRank) {
    if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
        if (getScreenWithId(screenId) == null) {
            Log.e(TAG, "Skipping child, screenId " + screenId + " not found");
            // DEBUGGING - Print out the stack trace to see where we are adding from
            new Throwable().printStackTrace();
            return;
        }
    }
    if (screenId == EXTRA_EMPTY_SCREEN_ID) {
        // This should never happen
        throw new RuntimeException("Screen id should not be EXTRA_EMPTY_SCREEN_ID");
    }

    final CellLayout layout;
    if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
        layout = mLauncher.getHotseat().getLayout();
        child.setOnKeyListener(null);

        // Hide folder title in the hotseat
        if (child instanceof FolderIcon) {
            ((FolderIcon) child).setTextVisible(false);
        }

        if (computeXYFromRank) {
            x = mLauncher.getHotseat().getCellXFromOrder((int) screenId);
            y = mLauncher.getHotseat().getCellYFromOrder((int) screenId);
        } else {
            screenId = mLauncher.getHotseat().getOrderInHotseat(x, y);
        }
    } else {
        // Show folder title if not in the hotseat
        if (child instanceof FolderIcon) {
            ((FolderIcon) child).setTextVisible(true);
        }
        layout = getScreenWithId(screenId);
        child.setOnKeyListener(new IconKeyEventListener());
    }

    ViewGroup.LayoutParams genericLp = child.getLayoutParams();
    CellLayout.LayoutParams lp;
    if (genericLp == null || !(genericLp instanceof CellLayout.LayoutParams)) {
        lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
    } else {
        lp = (CellLayout.LayoutParams) genericLp;
        lp.cellX = x;
        lp.cellY = y;
        lp.cellHSpan = spanX;
        lp.cellVSpan = spanY;
    }

    if (spanX < 0 && spanY < 0) {
        lp.isLockedToGrid = false;
    }

    // Get the canonical child id to uniquely represent this view in this screen
    int childId = LauncherModel.getCellLayoutChildId(container, screenId, x, y, spanX, spanY);
    boolean markCellsAsOccupied = !(child instanceof Folder);
    if (!layout.addViewToCellLayout(child, insert ? 0 : -1, childId, lp, markCellsAsOccupied)) {
        // TODO: This branch occurs when the workspace is adding views
        // outside of the defined grid
        // maybe we should be deleting these items from the LauncherModel?
        Launcher.addDumpLog(TAG, "Failed to add to item at (" + lp.cellX + "," + lp.cellY + ") to CellLayout",
                true);
    }

    if (!(child instanceof Folder)) {
        child.setHapticFeedbackEnabled(false);
        child.setOnLongClickListener(mLongClickListener);
    }
    if (child instanceof DropTarget) {
        mDragController.addDropTarget((DropTarget) child);
    }
}

From source file:cc.flydev.launcher.Workspace.java

/**
 * Drop an item that didn't originate on one of the workspace screens.
 * It may have come from Launcher (e.g. from all apps or customize), or it may have
 * come from another app altogether./*from  ww  w. j a  va2 s . c  om*/
 *
 * NOTE: This can also be called when we are outside of a drag event, when we want
 * to add an item to one of the workspace screens.
 */
private void onDropExternal(final int[] touchXY, final Object dragInfo, final CellLayout cellLayout,
        boolean insertAtFirst, DragObject d) {
    final Runnable exitSpringLoadedRunnable = new Runnable() {
        @Override
        public void run() {
            mLauncher.exitSpringLoadedDragModeDelayed(true, false, null);
        }
    };

    ItemInfo info = (ItemInfo) dragInfo;
    int spanX = info.spanX;
    int spanY = info.spanY;
    if (mDragInfo != null) {
        spanX = mDragInfo.spanX;
        spanY = mDragInfo.spanY;
    }

    final long container = mLauncher.isHotseatLayout(cellLayout) ? LauncherSettings.Favorites.CONTAINER_HOTSEAT
            : LauncherSettings.Favorites.CONTAINER_DESKTOP;
    final long screenId = getIdForScreen(cellLayout);
    if (!mLauncher.isHotseatLayout(cellLayout) && screenId != getScreenIdForPageIndex(mCurrentPage)
            && mState != State.SPRING_LOADED) {
        snapToScreenId(screenId, null);
    }

    if (info instanceof PendingAddItemInfo) {
        final PendingAddItemInfo pendingInfo = (PendingAddItemInfo) dragInfo;

        boolean findNearestVacantCell = true;
        if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
            mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, cellLayout,
                    mTargetCell);
            float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], mDragViewVisualCenter[1],
                    mTargetCell);
            if (willCreateUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell, distance, true)
                    || willAddToExistingUserFolder((ItemInfo) d.dragInfo, cellLayout, mTargetCell, distance)) {
                findNearestVacantCell = false;
            }
        }

        final ItemInfo item = (ItemInfo) d.dragInfo;
        boolean updateWidgetSize = false;
        if (findNearestVacantCell) {
            int minSpanX = item.spanX;
            int minSpanY = item.spanY;
            if (item.minSpanX > 0 && item.minSpanY > 0) {
                minSpanX = item.minSpanX;
                minSpanY = item.minSpanY;
            }
            int[] resultSpan = new int[2];
            mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
                    minSpanX, minSpanY, info.spanX, info.spanY, null, mTargetCell, resultSpan,
                    CellLayout.MODE_ON_DROP_EXTERNAL);

            if (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY) {
                updateWidgetSize = true;
            }
            item.spanX = resultSpan[0];
            item.spanY = resultSpan[1];
        }

        Runnable onAnimationCompleteRunnable = new Runnable() {
            @Override
            public void run() {
                // When dragging and dropping from customization tray, we deal with creating
                // widgets/shortcuts/folders in a slightly different way
                switch (pendingInfo.itemType) {
                case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
                    int span[] = new int[2];
                    span[0] = item.spanX;
                    span[1] = item.spanY;
                    mLauncher.addAppWidgetFromDrop((PendingAddWidgetInfo) pendingInfo, container, screenId,
                            mTargetCell, span, null);
                    break;
                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
                    mLauncher.processShortcutFromDrop(pendingInfo.componentName, container, screenId,
                            mTargetCell, null);
                    break;
                default:
                    throw new IllegalStateException("Unknown item type: " + pendingInfo.itemType);
                }
            }
        };
        View finalView = pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
                ? ((PendingAddWidgetInfo) pendingInfo).boundWidget
                : null;

        if (finalView instanceof AppWidgetHostView && updateWidgetSize) {
            AppWidgetHostView awhv = (AppWidgetHostView) finalView;
            AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, item.spanX, item.spanY);
        }

        int animationStyle = ANIMATE_INTO_POSITION_AND_DISAPPEAR;
        if (pendingInfo.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET
                && ((PendingAddWidgetInfo) pendingInfo).info.configure != null) {
            animationStyle = ANIMATE_INTO_POSITION_AND_REMAIN;
        }
        animateWidgetDrop(info, cellLayout, d.dragView, onAnimationCompleteRunnable, animationStyle, finalView,
                true);
    } else {
        // This is for other drag/drop cases, like dragging from All Apps
        View view = null;

        switch (info.itemType) {
        case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
        case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
            if (info.container == NO_ID && info instanceof AppInfo) {
                // Came from all apps -- make a copy
                info = new ShortcutInfo((AppInfo) info);
            }
            view = mLauncher.createShortcut(R.layout.application, cellLayout, (ShortcutInfo) info);
            break;
        case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
            view = FolderIcon.fromXml(R.layout.folder_icon, mLauncher, cellLayout, (FolderInfo) info,
                    mIconCache);
            break;
        default:
            throw new IllegalStateException("Unknown item type: " + info.itemType);
        }

        // First we find the cell nearest to point at which the item is
        // dropped, without any consideration to whether there is an item there.
        if (touchXY != null) {
            mTargetCell = findNearestArea((int) touchXY[0], (int) touchXY[1], spanX, spanY, cellLayout,
                    mTargetCell);
            float distance = cellLayout.getDistanceFromCell(mDragViewVisualCenter[0], mDragViewVisualCenter[1],
                    mTargetCell);
            d.postAnimationRunnable = exitSpringLoadedRunnable;
            if (createUserFolderIfNecessary(view, container, cellLayout, mTargetCell, distance, true,
                    d.dragView, d.postAnimationRunnable)) {
                return;
            }
            if (addToExistingFolderIfNecessary(view, cellLayout, mTargetCell, distance, d, true)) {
                return;
            }
        }

        if (touchXY != null) {
            // when dragging and dropping, just find the closest free spot
            mTargetCell = cellLayout.createArea((int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1],
                    1, 1, 1, 1, null, mTargetCell, null, CellLayout.MODE_ON_DROP_EXTERNAL);
        } else {
            cellLayout.findCellForSpan(mTargetCell, 1, 1);
        }
        addInScreen(view, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX, info.spanY,
                insertAtFirst);
        cellLayout.onDropChild(view);
        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) view.getLayoutParams();
        cellLayout.getShortcutsAndWidgets().measureChild(view);

        LauncherModel.addOrMoveItemInDatabase(mLauncher, info, container, screenId, lp.cellX, lp.cellY);

        if (d.dragView != null) {
            // We wrap the animation call in the temporary set and reset of the current
            // cellLayout to its final transform -- this means we animate the drag view to
            // the correct final location.
            setFinalTransitionTransform(cellLayout);
            mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, view, exitSpringLoadedRunnable);
            resetTransitionTransform(cellLayout);
        }
    }
}

From source file:android.support.v7.widget.RecyclerViewEx.java

Rect getItemDecorInsetsForChild(View child) {
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    if (!lp.mInsetsDirty) {
        return lp.mDecorInsets;
    }/*from w ww.j  ava  2s.c  o  m*/

    final Rect insets = lp.mDecorInsets;
    insets.set(0, 0, 0, 0);
    final int decorCount = mItemDecorations.size();
    for (int i = 0; i < decorCount; i++) {
        mTempRect.set(0, 0, 0, 0);
        mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
        insets.left += mTempRect.left;
        insets.top += mTempRect.top;
        insets.right += mTempRect.right;
        insets.bottom += mTempRect.bottom;
    }
    lp.mInsetsDirty = false;
    return insets;
}

From source file:android.support.v7.widget.RecyclerViewEx.java

void markItemDecorInsetsDirty() {
    final int childCount = mChildHelper.getUnfilteredChildCount();
    for (int i = 0; i < childCount; i++) {
        final View child = mChildHelper.getUnfilteredChildAt(i);
        ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
    }/*from w  ww  .  ja  v a2s  . com*/
    mRecycler.markItemDecorInsetsDirty();
}

From source file:cc.flydev.launcher.Workspace.java

public void onDrop(final DragObject d) {
    mDragViewVisualCenter = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView,
            mDragViewVisualCenter);/*from w  w w.  j a v a  2 s  .c  om*/

    CellLayout dropTargetLayout = mDropToLayout;

    // We want the point to be mapped to the dragTarget.
    if (dropTargetLayout != null) {
        if (mLauncher.isHotseatLayout(dropTargetLayout)) {
            mapPointFromSelfToHotseatLayout(mLauncher.getHotseat(), mDragViewVisualCenter);
        } else {
            mapPointFromSelfToChild(dropTargetLayout, mDragViewVisualCenter, null);
        }
    }

    int snapScreen = -1;
    boolean resizeOnDrop = false;
    if (d.dragSource != this) {
        final int[] touchXY = new int[] { (int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1] };
        onDropExternal(touchXY, d.dragInfo, dropTargetLayout, false, d);
    } else if (mDragInfo != null) {
        final View cell = mDragInfo.cell;

        Runnable resizeRunnable = null;
        if (dropTargetLayout != null && !d.cancelled) {
            // Move internally
            boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
            boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
            long container = hasMovedIntoHotseat ? LauncherSettings.Favorites.CONTAINER_HOTSEAT
                    : LauncherSettings.Favorites.CONTAINER_DESKTOP;
            long screenId = (mTargetCell[0] < 0) ? mDragInfo.screenId : getIdForScreen(dropTargetLayout);
            int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
            int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
            // First we find the cell nearest to point at which the item is
            // dropped, without any consideration to whether there is an item there.

            mTargetCell = findNearestArea((int) mDragViewVisualCenter[0], (int) mDragViewVisualCenter[1], spanX,
                    spanY, dropTargetLayout, mTargetCell);
            float distance = dropTargetLayout.getDistanceFromCell(mDragViewVisualCenter[0],
                    mDragViewVisualCenter[1], mTargetCell);

            // If the item being dropped is a shortcut and the nearest drop
            // cell also contains a shortcut, then create a folder with the two shortcuts.
            if (!mInScrollArea && createUserFolderIfNecessary(cell, container, dropTargetLayout, mTargetCell,
                    distance, false, d.dragView, null)) {
                stripEmptyScreens();
                return;
            }

            if (addToExistingFolderIfNecessary(cell, dropTargetLayout, mTargetCell, distance, d, false)) {
                stripEmptyScreens();
                return;
            }

            // Aside from the special case where we're dropping a shortcut onto a shortcut,
            // we need to find the nearest cell location that is vacant
            ItemInfo item = (ItemInfo) d.dragInfo;
            int minSpanX = item.spanX;
            int minSpanY = item.spanY;
            if (item.minSpanX > 0 && item.minSpanY > 0) {
                minSpanX = item.minSpanX;
                minSpanY = item.minSpanY;
            }

            int[] resultSpan = new int[2];
            mTargetCell = dropTargetLayout.createArea((int) mDragViewVisualCenter[0],
                    (int) mDragViewVisualCenter[1], minSpanX, minSpanY, spanX, spanY, cell, mTargetCell,
                    resultSpan, CellLayout.MODE_ON_DROP);

            boolean foundCell = mTargetCell[0] >= 0 && mTargetCell[1] >= 0;

            // if the widget resizes on drop
            if (foundCell && (cell instanceof AppWidgetHostView)
                    && (resultSpan[0] != item.spanX || resultSpan[1] != item.spanY)) {
                resizeOnDrop = true;
                item.spanX = resultSpan[0];
                item.spanY = resultSpan[1];
                AppWidgetHostView awhv = (AppWidgetHostView) cell;
                AppWidgetResizeFrame.updateWidgetSizeRanges(awhv, mLauncher, resultSpan[0], resultSpan[1]);
            }

            if (getScreenIdForPageIndex(mCurrentPage) != screenId && !hasMovedIntoHotseat) {
                snapScreen = getPageIndexForScreenId(screenId);
                snapToPage(snapScreen);
            }

            if (foundCell) {
                final ItemInfo info = (ItemInfo) cell.getTag();
                if (hasMovedLayouts) {
                    // Reparent the view
                    getParentCellLayoutForView(cell).removeView(cell);
                    addInScreen(cell, container, screenId, mTargetCell[0], mTargetCell[1], info.spanX,
                            info.spanY);
                }

                // update the item's position after drop
                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
                lp.cellX = lp.tmpCellX = mTargetCell[0];
                lp.cellY = lp.tmpCellY = mTargetCell[1];
                lp.cellHSpan = item.spanX;
                lp.cellVSpan = item.spanY;
                lp.isLockedToGrid = true;
                cell.setId(LauncherModel.getCellLayoutChildId(container, mDragInfo.screenId, mTargetCell[0],
                        mTargetCell[1], mDragInfo.spanX, mDragInfo.spanY));

                if (container != LauncherSettings.Favorites.CONTAINER_HOTSEAT
                        && cell instanceof LauncherAppWidgetHostView) {
                    final CellLayout cellLayout = dropTargetLayout;
                    // We post this call so that the widget has a chance to be placed
                    // in its final location

                    final LauncherAppWidgetHostView hostView = (LauncherAppWidgetHostView) cell;
                    AppWidgetProviderInfo pinfo = hostView.getAppWidgetInfo();
                    if (pinfo != null && pinfo.resizeMode != AppWidgetProviderInfo.RESIZE_NONE) {
                        final Runnable addResizeFrame = new Runnable() {
                            public void run() {
                                DragLayer dragLayer = mLauncher.getDragLayer();
                                dragLayer.addResizeFrame(info, hostView, cellLayout);
                            }
                        };
                        resizeRunnable = (new Runnable() {
                            public void run() {
                                if (!isPageMoving()) {
                                    addResizeFrame.run();
                                } else {
                                    mDelayedResizeRunnable = addResizeFrame;
                                }
                            }
                        });
                    }
                }

                LauncherModel.modifyItemInDatabase(mLauncher, info, container, screenId, lp.cellX, lp.cellY,
                        item.spanX, item.spanY);
            } else {
                // If we can't find a drop location, we return the item to its original position
                CellLayout.LayoutParams lp = (CellLayout.LayoutParams) cell.getLayoutParams();
                mTargetCell[0] = lp.cellX;
                mTargetCell[1] = lp.cellY;
                CellLayout layout = (CellLayout) cell.getParent().getParent();
                layout.markCellsAsOccupiedForView(cell);
            }
        }

        final CellLayout parent = (CellLayout) cell.getParent().getParent();
        final Runnable finalResizeRunnable = resizeRunnable;
        // Prepare it to be animated into its new position
        // This must be called after the view has been re-parented
        final Runnable onCompleteRunnable = new Runnable() {
            @Override
            public void run() {
                mAnimatingViewIntoPlace = false;
                updateChildrenLayersEnabled(false);
                if (finalResizeRunnable != null) {
                    finalResizeRunnable.run();
                }
                stripEmptyScreens();
            }
        };
        mAnimatingViewIntoPlace = true;
        if (d.dragView.hasDrawn()) {
            final ItemInfo info = (ItemInfo) cell.getTag();
            if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET) {
                int animationType = resizeOnDrop ? ANIMATE_INTO_POSITION_AND_RESIZE
                        : ANIMATE_INTO_POSITION_AND_DISAPPEAR;
                animateWidgetDrop(info, parent, d.dragView, onCompleteRunnable, animationType, cell, false);
            } else {
                int duration = snapScreen < 0 ? -1 : ADJACENT_SCREEN_DROP_DURATION;
                mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, cell, duration, onCompleteRunnable,
                        this);
            }
        } else {
            d.deferDragViewCleanupPostAnimation = false;
            cell.setVisibility(VISIBLE);
        }
        parent.onDropChild(cell);
    }
}