Example usage for android.view View getMeasuredWidth

List of usage examples for android.view View getMeasuredWidth

Introduction

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

Prototype

public final int getMeasuredWidth() 

Source Link

Document

Like #getMeasuredWidthAndState() , but only returns the raw width component (that is the result is masked by #MEASURED_SIZE_MASK ).

Usage

From source file:com.csusm.twinder.Fragment.QRScanFragment.java

private void onCreateDetector(@NonNull final View view) {
    final Context context = view.getContext().getApplicationContext();
    final BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
    barcodeDetector.setProcessor(new MultiProcessor.Builder<>(new MultiProcessor.Factory<Barcode>() {
        @Override//from   w  ww  .j a v a 2s .  c  om
        public Tracker<Barcode> create(final Barcode barcode) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCallback.onScanComplete(barcode.displayValue);
                    mPreview.stop();

                    Intent intent = new Intent(getContext(), ScanSuccessActivity.class);
                    intent.putExtra("BARCODE", barcode.displayValue);

                    QRScanFragment.this.startActivity(intent);

                }
            });
            return new Tracker<>();
        }
    }).build());

    if (!barcodeDetector.isOperational()) {
        IntentFilter lowStorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
        if (context.registerReceiver(null, lowStorageFilter) != null) {
            // Low storage
            mCallback.onCameraError(R.string.camera_error_low_storage);
        } else {
            // Native libs unavailable
            mCallback.onCameraError(R.string.camera_error_dependencies);
        }
        return;
    }

    final ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }

            CameraSource.Builder builder = new CameraSource.Builder(context, barcodeDetector)
                    .setFacing(CameraSource.CAMERA_FACING_BACK)
                    .setRequestedPreviewSize(view.getMeasuredWidth(), view.getMeasuredHeight())
                    .setRequestedFps(30.0f);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                builder = builder.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            }

            mCameraSource = builder.build();
            startCameraSource();
        }
    });
}

From source file:com.android.launcher2.PagedView.java

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    if (!mIsDataReady) {
        return;// ww  w . j a  v a 2s . co  m
    }

    if (DEBUG)
        Log.d(TAG, "PagedView.onLayout()");
    final int verticalPadding = getPaddingTop() + getPaddingBottom();
    final int childCount = getChildCount();
    int childLeft = getRelativeChildOffset(0);

    for (int i = 0; i < childCount; i++) {
        final View child = getPageAt(i);
        if (child.getVisibility() != View.GONE) {
            final int childWidth = getScaledMeasuredWidth(child);
            final int childHeight = child.getMeasuredHeight();
            int childTop = getPaddingTop();
            if (mCenterPagesVertically) {
                childTop += ((getMeasuredHeight() - verticalPadding) - childHeight) / 2;
            }

            if (DEBUG)
                Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
            child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + childHeight);
            childLeft += childWidth + mPageSpacing;
        }
    }

    if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
        setHorizontalScrollBarEnabled(false);
        updateCurrentPageScroll();
        setHorizontalScrollBarEnabled(true);
        mFirstLayout = false;
    }
}

From source file:com.google.android.flexbox.FlexboxHelper.java

/**
 * Shrink the flex items along the main axis based on the individual mFlexShrink attribute.
 *
 * @param widthMeasureSpec     the horizontal space requirements as imposed by the parent
 * @param heightMeasureSpec    the vertical space requirements as imposed by the parent
 * @param flexLine             the flex line to which flex items belong
 * @param maxMainSize          the maximum main size. Shrank main size will be this size
 * @param paddingAlongMainAxis the padding value along the main axis
 * @param calledRecursively    true if this method is called recursively, false otherwise
 * @see FlexContainer#getFlexDirection()
 * @see FlexContainer#setFlexDirection(int)
 * @see FlexItem#getFlexShrink()/*from   w w  w .j  av a 2  s  .c om*/
 */
private void shrinkFlexItems(int widthMeasureSpec, int heightMeasureSpec, FlexLine flexLine, int maxMainSize,
        int paddingAlongMainAxis, boolean calledRecursively) {
    int sizeBeforeShrink = flexLine.mMainSize;
    if (flexLine.mTotalFlexShrink <= 0 || maxMainSize > flexLine.mMainSize) {
        return;
    }
    boolean needsReshrink = false;
    float unitShrink = (flexLine.mMainSize - maxMainSize) / flexLine.mTotalFlexShrink;
    float accumulatedRoundError = 0;
    flexLine.mMainSize = paddingAlongMainAxis + flexLine.mDividerLengthInMainSize;

    // Setting the cross size of the flex line as the temporal value since the cross size of
    // each flex item may be changed from the initial calculation
    // (in the measureHorizontal/measureVertical method) even this method is part of the main
    // size determination.
    // E.g. If a TextView's layout_width is set to 0dp, layout_height is set to wrap_content,
    // and layout_flexGrow is set to 1, the TextView is trying to expand to the vertical
    // direction to enclose its content (in the measureHorizontal method), but
    // the width will be expanded in this method. In that case, the height needs to be measured
    // again with the expanded width.
    int largestCrossSize = 0;
    if (!calledRecursively) {
        flexLine.mCrossSize = Integer.MIN_VALUE;
    }
    for (int i = 0; i < flexLine.mItemCount; i++) {
        int index = flexLine.mFirstIndex + i;
        View child = mFlexContainer.getReorderedFlexItemAt(index);
        if (child == null || child.getVisibility() == View.GONE) {
            continue;
        }
        FlexItem flexItem = (FlexItem) child.getLayoutParams();
        int flexDirection = mFlexContainer.getFlexDirection();
        if (flexDirection == FlexDirection.ROW || flexDirection == FlexDirection.ROW_REVERSE) {
            // The direction of main axis is horizontal

            int childMeasuredWidth = child.getMeasuredWidth();
            if (mMeasuredSizeCache != null) {
                // Retrieve the measured width from the cache because there
                // are some cases that the view is re-created from the last measure, thus
                // View#getMeasuredWidth returns 0.
                // E.g. if the flex container is FlexboxLayoutManager, the case happens
                // frequently
                childMeasuredWidth = extractLowerInt(mMeasuredSizeCache[index]);
            }
            int childMeasuredHeight = child.getMeasuredHeight();
            if (mMeasuredSizeCache != null) {
                // Extract the measured height from the cache
                childMeasuredHeight = extractHigherInt(mMeasuredSizeCache[index]);
            }
            if (!mChildrenFrozen[index] && flexItem.getFlexShrink() > 0f) {
                float rawCalculatedWidth = childMeasuredWidth - unitShrink * flexItem.getFlexShrink();
                if (i == flexLine.mItemCount - 1) {
                    rawCalculatedWidth += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newWidth = Math.round(rawCalculatedWidth);
                if (newWidth < flexItem.getMinWidth()) {
                    // This means the child doesn't have enough space to distribute the negative
                    // free space. To adjust the flex line length down to the maxMainSize,
                    // remaining
                    // negative free space needs to be re-distributed to other flex items
                    // (children views). In that case, invoke this method again with the same
                    // fromIndex.
                    needsReshrink = true;
                    newWidth = flexItem.getMinWidth();
                    mChildrenFrozen[index] = true;
                    flexLine.mTotalFlexShrink -= flexItem.getFlexShrink();
                } else {
                    accumulatedRoundError += (rawCalculatedWidth - newWidth);
                    if (accumulatedRoundError > 1.0) {
                        newWidth += 1;
                        accumulatedRoundError -= 1;
                    } else if (accumulatedRoundError < -1.0) {
                        newWidth -= 1;
                        accumulatedRoundError += 1;
                    }
                }
                int childHeightMeasureSpec = getChildHeightMeasureSpecInternal(heightMeasureSpec, flexItem,
                        flexLine.mSumCrossSizeBefore);
                int childWidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(newWidth,
                        View.MeasureSpec.EXACTLY);
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

                childMeasuredWidth = child.getMeasuredWidth();
                childMeasuredHeight = child.getMeasuredHeight();
                updateMeasureCache(index, childWidthMeasureSpec, childHeightMeasureSpec, child);
                mFlexContainer.updateViewCache(index, child);
            }
            largestCrossSize = Math.max(largestCrossSize, childMeasuredHeight + flexItem.getMarginTop()
                    + flexItem.getMarginBottom() + mFlexContainer.getDecorationLengthCrossAxis(child));
            flexLine.mMainSize += childMeasuredWidth + flexItem.getMarginLeft() + flexItem.getMarginRight();
        } else {
            // The direction of main axis is vertical

            int childMeasuredHeight = child.getMeasuredHeight();
            if (mMeasuredSizeCache != null) {
                // Retrieve the measured height from the cache because there
                // are some cases that the view is re-created from the last measure, thus
                // View#getMeasuredHeight returns 0.
                // E.g. if the flex container is FlexboxLayoutManager, that case happens
                // frequently
                childMeasuredHeight = extractHigherInt(mMeasuredSizeCache[index]);
            }
            int childMeasuredWidth = child.getMeasuredWidth();
            if (mMeasuredSizeCache != null) {
                // Extract the measured width from the cache
                childMeasuredWidth = extractLowerInt(mMeasuredSizeCache[index]);
            }
            if (!mChildrenFrozen[index] && flexItem.getFlexShrink() > 0f) {
                float rawCalculatedHeight = childMeasuredHeight - unitShrink * flexItem.getFlexShrink();
                if (i == flexLine.mItemCount - 1) {
                    rawCalculatedHeight += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newHeight = Math.round(rawCalculatedHeight);
                if (newHeight < flexItem.getMinHeight()) {
                    // Need to invoke this method again like the case flex direction is vertical
                    needsReshrink = true;
                    newHeight = flexItem.getMinHeight();
                    mChildrenFrozen[index] = true;
                    flexLine.mTotalFlexShrink -= flexItem.getFlexShrink();
                } else {
                    accumulatedRoundError += (rawCalculatedHeight - newHeight);
                    if (accumulatedRoundError > 1.0) {
                        newHeight += 1;
                        accumulatedRoundError -= 1;
                    } else if (accumulatedRoundError < -1.0) {
                        newHeight -= 1;
                        accumulatedRoundError += 1;
                    }
                }
                int childWidthMeasureSpec = getChildWidthMeasureSpecInternal(widthMeasureSpec, flexItem,
                        flexLine.mSumCrossSizeBefore);
                int childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(newHeight,
                        View.MeasureSpec.EXACTLY);
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

                childMeasuredWidth = child.getMeasuredWidth();
                childMeasuredHeight = child.getMeasuredHeight();
                updateMeasureCache(index, childWidthMeasureSpec, childHeightMeasureSpec, child);
                mFlexContainer.updateViewCache(index, child);
            }
            largestCrossSize = Math.max(largestCrossSize, childMeasuredWidth + flexItem.getMarginLeft()
                    + flexItem.getMarginRight() + mFlexContainer.getDecorationLengthCrossAxis(child));
            flexLine.mMainSize += childMeasuredHeight + flexItem.getMarginTop() + flexItem.getMarginBottom();
        }
        flexLine.mCrossSize = Math.max(flexLine.mCrossSize, largestCrossSize);
    }

    if (needsReshrink && sizeBeforeShrink != flexLine.mMainSize) {
        // Re-invoke the method with the same fromIndex to distribute the negative free space
        // that wasn't fully distributed (because some views length were not enough)
        shrinkFlexItems(widthMeasureSpec, heightMeasureSpec, flexLine, maxMainSize, paddingAlongMainAxis, true);
    }
}

From source file:com.google.android.flexbox.FlexboxHelper.java

/**
 * Expand the flex items along the main axis based on the individual mFlexGrow attribute.
 *
 * @param widthMeasureSpec     the horizontal space requirements as imposed by the parent
 * @param heightMeasureSpec    the vertical space requirements as imposed by the parent
 * @param flexLine             the flex line to which flex items belong
 * @param maxMainSize          the maximum main size. Expanded main size will be this size
 * @param paddingAlongMainAxis the padding value along the main axis
 * @param calledRecursively    true if this method is called recursively, false otherwise
 * @see FlexContainer#getFlexDirection()
 * @see FlexContainer#setFlexDirection(int)
 * @see FlexItem#getFlexGrow()/* ww w.j  a v  a 2  s  .c o m*/
 */
private void expandFlexItems(int widthMeasureSpec, int heightMeasureSpec, FlexLine flexLine, int maxMainSize,
        int paddingAlongMainAxis, boolean calledRecursively) {
    if (flexLine.mTotalFlexGrow <= 0 || maxMainSize < flexLine.mMainSize) {
        return;
    }
    int sizeBeforeExpand = flexLine.mMainSize;
    boolean needsReexpand = false;
    float unitSpace = (maxMainSize - flexLine.mMainSize) / flexLine.mTotalFlexGrow;
    flexLine.mMainSize = paddingAlongMainAxis + flexLine.mDividerLengthInMainSize;

    // Setting the cross size of the flex line as the temporal value since the cross size of
    // each flex item may be changed from the initial calculation
    // (in the measureHorizontal/measureVertical method) even this method is part of the main
    // size determination.
    // E.g. If a TextView's layout_width is set to 0dp, layout_height is set to wrap_content,
    // and layout_flexGrow is set to 1, the TextView is trying to expand to the vertical
    // direction to enclose its content (in the measureHorizontal method), but
    // the width will be expanded in this method. In that case, the height needs to be measured
    // again with the expanded width.
    int largestCrossSize = 0;
    if (!calledRecursively) {
        flexLine.mCrossSize = Integer.MIN_VALUE;
    }
    float accumulatedRoundError = 0;
    for (int i = 0; i < flexLine.mItemCount; i++) {
        int index = flexLine.mFirstIndex + i;
        View child = mFlexContainer.getReorderedFlexItemAt(index);
        if (child == null || child.getVisibility() == View.GONE) {
            continue;
        }
        FlexItem flexItem = (FlexItem) child.getLayoutParams();
        int flexDirection = mFlexContainer.getFlexDirection();
        if (flexDirection == FlexDirection.ROW || flexDirection == FlexDirection.ROW_REVERSE) {
            // The direction of the main axis is horizontal

            int childMeasuredWidth = child.getMeasuredWidth();
            if (mMeasuredSizeCache != null) {
                // Retrieve the measured width from the cache because there
                // are some cases that the view is re-created from the last measure, thus
                // View#getMeasuredWidth returns 0.
                // E.g. if the flex container is FlexboxLayoutManager, the case happens
                // frequently
                childMeasuredWidth = extractLowerInt(mMeasuredSizeCache[index]);
            }
            int childMeasuredHeight = child.getMeasuredHeight();
            if (mMeasuredSizeCache != null) {
                // Extract the measured height from the cache
                childMeasuredHeight = extractHigherInt(mMeasuredSizeCache[index]);
            }
            if (!mChildrenFrozen[index] && flexItem.getFlexGrow() > 0f) {
                float rawCalculatedWidth = childMeasuredWidth + unitSpace * flexItem.getFlexGrow();
                if (i == flexLine.mItemCount - 1) {
                    rawCalculatedWidth += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newWidth = Math.round(rawCalculatedWidth);
                if (newWidth > flexItem.getMaxWidth()) {
                    // This means the child can't expand beyond the value of the mMaxWidth
                    // attribute.
                    // To adjust the flex line length to the size of maxMainSize, remaining
                    // positive free space needs to be re-distributed to other flex items
                    // (children views). In that case, invoke this method again with the same
                    // fromIndex.
                    needsReexpand = true;
                    newWidth = flexItem.getMaxWidth();
                    mChildrenFrozen[index] = true;
                    flexLine.mTotalFlexGrow -= flexItem.getFlexGrow();
                } else {
                    accumulatedRoundError += (rawCalculatedWidth - newWidth);
                    if (accumulatedRoundError > 1.0) {
                        newWidth += 1;
                        accumulatedRoundError -= 1.0;
                    } else if (accumulatedRoundError < -1.0) {
                        newWidth -= 1;
                        accumulatedRoundError += 1.0;
                    }
                }
                int childHeightMeasureSpec = getChildHeightMeasureSpecInternal(heightMeasureSpec, flexItem,
                        flexLine.mSumCrossSizeBefore);
                int childWidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(newWidth,
                        View.MeasureSpec.EXACTLY);
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
                childMeasuredWidth = child.getMeasuredWidth();
                childMeasuredHeight = child.getMeasuredHeight();
                updateMeasureCache(index, childWidthMeasureSpec, childHeightMeasureSpec, child);
                mFlexContainer.updateViewCache(index, child);
            }
            largestCrossSize = Math.max(largestCrossSize, childMeasuredHeight + flexItem.getMarginTop()
                    + flexItem.getMarginBottom() + mFlexContainer.getDecorationLengthCrossAxis(child));
            flexLine.mMainSize += childMeasuredWidth + flexItem.getMarginLeft() + flexItem.getMarginRight();
        } else {
            // The direction of the main axis is vertical

            int childMeasuredHeight = child.getMeasuredHeight();
            if (mMeasuredSizeCache != null) {
                // Retrieve the measured height from the cache because there
                // are some cases that the view is re-created from the last measure, thus
                // View#getMeasuredHeight returns 0.
                // E.g. if the flex container is FlexboxLayoutManager, that case happens
                // frequently
                childMeasuredHeight = extractHigherInt(mMeasuredSizeCache[index]);
            }
            int childMeasuredWidth = child.getMeasuredWidth();
            if (mMeasuredSizeCache != null) {
                // Extract the measured width from the cache
                childMeasuredWidth = extractLowerInt(mMeasuredSizeCache[index]);
            }
            if (!mChildrenFrozen[index] && flexItem.getFlexGrow() > 0f) {
                float rawCalculatedHeight = childMeasuredHeight + unitSpace * flexItem.getFlexGrow();
                if (i == flexLine.mItemCount - 1) {
                    rawCalculatedHeight += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newHeight = Math.round(rawCalculatedHeight);
                if (newHeight > flexItem.getMaxHeight()) {
                    // This means the child can't expand beyond the value of the mMaxHeight
                    // attribute.
                    // To adjust the flex line length to the size of maxMainSize, remaining
                    // positive free space needs to be re-distributed to other flex items
                    // (children views). In that case, invoke this method again with the same
                    // fromIndex.
                    needsReexpand = true;
                    newHeight = flexItem.getMaxHeight();
                    mChildrenFrozen[index] = true;
                    flexLine.mTotalFlexGrow -= flexItem.getFlexGrow();
                } else {
                    accumulatedRoundError += (rawCalculatedHeight - newHeight);
                    if (accumulatedRoundError > 1.0) {
                        newHeight += 1;
                        accumulatedRoundError -= 1.0;
                    } else if (accumulatedRoundError < -1.0) {
                        newHeight -= 1;
                        accumulatedRoundError += 1.0;
                    }
                }
                int childWidthMeasureSpec = getChildWidthMeasureSpecInternal(widthMeasureSpec, flexItem,
                        flexLine.mSumCrossSizeBefore);
                int childHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(newHeight,
                        View.MeasureSpec.EXACTLY);
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
                childMeasuredWidth = child.getMeasuredWidth();
                childMeasuredHeight = child.getMeasuredHeight();
                updateMeasureCache(index, childWidthMeasureSpec, childHeightMeasureSpec, child);
                mFlexContainer.updateViewCache(index, child);
            }
            largestCrossSize = Math.max(largestCrossSize, childMeasuredWidth + flexItem.getMarginLeft()
                    + flexItem.getMarginRight() + mFlexContainer.getDecorationLengthCrossAxis(child));
            flexLine.mMainSize += childMeasuredHeight + flexItem.getMarginTop() + flexItem.getMarginBottom();
        }
        flexLine.mCrossSize = Math.max(flexLine.mCrossSize, largestCrossSize);
    }

    if (needsReexpand && sizeBeforeExpand != flexLine.mMainSize) {
        // Re-invoke the method with the same flex line to distribute the positive free space
        // that wasn't fully distributed (because of maximum length constraint)
        expandFlexItems(widthMeasureSpec, heightMeasureSpec, flexLine, maxMainSize, paddingAlongMainAxis, true);
    }
}

From source file:android.support.design.widget.RaeTabLayout.java

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // If we have a MeasureSpec which allows us to decide our height, try and use the default
    // height/*  ww  w  .  j av  a2s . com*/
    final int idealHeight = dpToPx(getDefaultHeight()) + getPaddingTop() + getPaddingBottom();
    switch (MeasureSpec.getMode(heightMeasureSpec)) {
    case MeasureSpec.AT_MOST:
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(
                Math.min(idealHeight, MeasureSpec.getSize(heightMeasureSpec)), MeasureSpec.EXACTLY);
        break;
    case MeasureSpec.UNSPECIFIED:
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(idealHeight, MeasureSpec.EXACTLY);
        break;
    }

    final int specWidth = MeasureSpec.getSize(widthMeasureSpec);
    if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED) {
        // If we don't have an unspecified width spec, use the given size to calculate
        // the max tab width
        mTabMaxWidth = mRequestedTabMaxWidth > 0 ? mRequestedTabMaxWidth
                : specWidth - dpToPx(TAB_MIN_WIDTH_MARGIN);
    }

    // Now super measure itself using the (possibly) modified height spec
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    if (getChildCount() == 1) {
        // If we're in fixed mode then we need to make the tab strip is the same width as us
        // so we don't scroll
        final View child = getChildAt(0);
        boolean remeasure = false;

        switch (mMode) {
        case MODE_SCROLLABLE:
            // We only need to resize the child if it's smaller than us. This is similar
            // to fillViewport
            remeasure = child.getMeasuredWidth() < getMeasuredWidth();
            break;
        case MODE_FIXED:
            // Resize the child so that it doesn't scroll
            remeasure = child.getMeasuredWidth() != getMeasuredWidth();
            break;
        }

        if (remeasure) {
            // Re-measure the child with a widthSpec set to be exactly our measure width
            int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                    getPaddingTop() + getPaddingBottom(), child.getLayoutParams().height);
            int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY);
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}

From source file:com.android.leanlauncher.Workspace.java

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    Log.d(TAG, "OnLayout> " + getChildCount());
    if (getChildCount() == 0) {
        return;/*  w  w  w.  ja  va 2s.  co m*/
    }

    int offsetX = mWorkspace.getMeasuredWidth();
    int offsetY = mWorkspace.getMeasuredHeight();

    // Update the viewport offsets
    mViewPort.offset(offsetX, offsetY);

    final View child = getChildAt(0);
    if (child.getVisibility() != View.GONE) {
        child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
    }
}

From source file:com.android.widget.SlidingPaneLayout.java

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    if (heightMode != MeasureSpec.EXACTLY) {
        if (isInEditMode()) {
            // Don't crash the layout editor. Consume all of the space if specified
            // or pick a magic number from thin air otherwise.
            // TODO Better communication with tools of this bogus state.
            // It will crash on a real device.
            if (heightMode == MeasureSpec.AT_MOST) {
                heightMode = MeasureSpec.EXACTLY;
            } else if (heightMode == MeasureSpec.UNSPECIFIED) {
                heightMode = 300;//from  w  w  w . j a  v a 2  s .c  o  m
            }
        } else {
            throw new IllegalStateException("Height must have an exact value or MATCH_PARENT");
        }
    } else if (widthMode == MeasureSpec.UNSPECIFIED) {
        if (isInEditMode()) {
            // Don't crash the layout editor. Pick a magic number from thin air instead.
            // TODO Better communication with tools of this bogus state.
            // It will crash on a real device.
            if (widthMode == MeasureSpec.UNSPECIFIED) {
                widthMode = 300;
            }
        } else {
            throw new IllegalStateException("Width must not be UNSPECIFIED");
        }
    }

    int layoutWidth = 0;
    int maxLayoutWidth = -1;
    switch (widthMode) {
    case MeasureSpec.EXACTLY:
        layoutWidth = maxLayoutWidth = widthSize - getPaddingLeft() - getPaddingRight();
        break;
    case MeasureSpec.AT_MOST:
        maxLayoutWidth = widthSize - getPaddingLeft() - getPaddingRight();
        break;
    }

    boolean canSlide = false;
    final int heightAvailable = heightSize - getPaddingTop() - getPaddingBottom();
    final int childCount = getChildCount();

    if (childCount > 2) {
        Log.e(TAG, "onMeasure: More than two child views are not supported.");
    }

    // We'll find the current one below.
    mSlideableView = null;

    // First pass. Measure based on child LayoutParams width/height.
    for (int i = 0; i < childCount; i++) {
        final View child = getChildAt(i);
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();

        if (child.getVisibility() == GONE) {
            continue;
        }

        int childHeightSpec;
        final int verticalMargin = lp.topMargin + lp.bottomMargin;
        if (lp.height == LayoutParams.WRAP_CONTENT) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(heightAvailable - verticalMargin,
                    MeasureSpec.AT_MOST);
        } else if (lp.height == LayoutParams.MATCH_PARENT) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(heightAvailable - verticalMargin,
                    MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
        }

        int childWidthSpec;
        if (lp.width == LayoutParams.WRAP_CONTENT) {
            childWidthSpec = MeasureSpec.makeMeasureSpec(maxLayoutWidth, MeasureSpec.AT_MOST);
        } else if (lp.width == LayoutParams.MATCH_PARENT) {
            childWidthSpec = MeasureSpec.makeMeasureSpec(maxLayoutWidth, MeasureSpec.EXACTLY);
        } else {
            childWidthSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
        }

        child.measure(childWidthSpec, childHeightSpec);
        final int childWidth = child.getMeasuredWidth();

        if (widthMode == MeasureSpec.AT_MOST && childWidth > layoutWidth) {
            layoutWidth = Math.min(childWidth, maxLayoutWidth);
        }

        if (i == childCount - 1) {
            canSlide |= lp.slideable = true;
            mSlideableView = child;
        }
    }

    final int measuredHeight = heightSize;
    final int measuredWidth = layoutWidth + getPaddingLeft() + getPaddingRight();

    setMeasuredDimension(measuredWidth, measuredHeight);
    mCanSlide = canSlide;

    if (mDragHelper.getViewDragState() != ViewDragHelper.STATE_IDLE && !canSlide) {
        // Cancel scrolling in progress, it's no longer relevant.
        mDragHelper.abort();
    }
}

From source file:android.widget.Gallery.java

/**
 * Helper for makeAndAddView to set the position of a view and fill out its
 * layout parameters./*ww  w  . j  a  va 2 s  .  c o  m*/
 * 
 * @param child The view to position
 * @param offset Offset from the selected position
 * @param x X-coordinate indicating where this view should be placed. This
 *        will either be the left or right edge of the view, depending on
 *        the fromLeft parameter
 * @param fromLeft Are we positioning views based on the left edge? (i.e.,
 *        building from left to right)?
 */
private void setUpChild(View child, int offset, int x, boolean fromLeft) {

    // Respect layout params that are already in the view. Otherwise
    // make some up...
    Gallery.LayoutParams lp = (Gallery.LayoutParams) child.getLayoutParams();
    if (lp == null) {
        lp = (Gallery.LayoutParams) generateDefaultLayoutParams();
    }

    addViewInLayout(child, fromLeft != mIsRtl ? -1 : 0, lp);

    child.setSelected(offset == 0);

    // Get measure specs
    int childHeightSpec = ViewGroup.getChildMeasureSpec(mHeightMeasureSpec,
            mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height);
    int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
            mSpinnerPadding.left + mSpinnerPadding.right, lp.width);

    // Measure child
    child.measure(childWidthSpec, childHeightSpec);

    int childLeft;
    int childRight;

    // Position vertically based on gravity setting
    int childTop = calculateTop(child, true);
    int childBottom = childTop + child.getMeasuredHeight();

    int width = child.getMeasuredWidth();
    if (fromLeft) {
        childLeft = x;
        childRight = childLeft + width;
    } else {
        childLeft = x - width;
        childRight = x;
    }

    child.layout(childLeft, childTop, childRight, childBottom);
}

From source file:com.devabit.takestock.ui.widget.FlexboxLayout.java

/**
 * Shrink the flex items along the main axis based on the individual flexShrink attribute.
 *
 * @param flexLine             the flex line to which flex items belong
 * @param flexDirection        the flexDirection value for this FlexboxLayout
 * @param maxMainSize          the maximum main size. Shrank main size will be this size
 * @param paddingAlongMainAxis the padding value along the main axis
 * @param startIndex           the start index of the children views to be shrank. This index
 *                             needs to/*w  w  w.j  a v  a  2 s .  com*/
 *                             be an absolute index in the flex container (FlexboxLayout),
 *                             not the relative index in the flex line.
 * @return the next index, the next flex line's first flex item starts from the returned index
 * @see #getFlexDirection()
 * @see #setFlexDirection(int)
 * @see LayoutParams#flexShrink
 */
private int shrinkFlexItems(FlexLine flexLine, @FlexDirection int flexDirection, int maxMainSize,
        int paddingAlongMainAxis, int startIndex) {
    int childIndex = startIndex;
    int sizeBeforeShrink = flexLine.mainSize;
    if (flexLine.totalFlexShrink <= 0 || maxMainSize > flexLine.mainSize) {
        childIndex += flexLine.itemCount;
        return childIndex;
    }
    boolean needsReshrink = false;
    float unitShrink = (flexLine.mainSize - maxMainSize) / flexLine.totalFlexShrink;
    float accumulatedRoundError = 0;
    flexLine.mainSize = paddingAlongMainAxis;
    for (int i = 0; i < flexLine.itemCount; i++) {
        View child = getReorderedChildAt(childIndex);
        if (child == null) {
            continue;
        } else if (child.getVisibility() == View.GONE) {
            childIndex++;
            continue;
        }
        LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (flexDirection == FLEX_DIRECTION_ROW || flexDirection == FLEX_DIRECTION_ROW_REVERSE) {
            // The direction of main axis is horizontal
            if (!mChildrenFrozen[childIndex]) {
                float rawCalculatedWidth = child.getMeasuredWidth() - unitShrink * lp.flexShrink;
                if (i == flexLine.itemCount - 1) {
                    rawCalculatedWidth += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newWidth = Math.round(rawCalculatedWidth);
                if (newWidth < lp.minWidth) {
                    // This means the child doesn't have enough space to distribute the negative
                    // free space. To adjust the flex line length down to the maxMainSize, remaining
                    // negative free space needs to be re-distributed to other flex items
                    // (children views). In that case, invoke this method again with the same
                    // startIndex.
                    needsReshrink = true;
                    newWidth = lp.minWidth;
                    mChildrenFrozen[childIndex] = true;
                    flexLine.totalFlexShrink -= lp.flexShrink;
                } else {
                    accumulatedRoundError += (rawCalculatedWidth - newWidth);
                    if (accumulatedRoundError > 1.0) {
                        newWidth += 1;
                        accumulatedRoundError -= 1;
                    } else if (accumulatedRoundError < -1.0) {
                        newWidth -= 1;
                        accumulatedRoundError += 1;
                    }
                }
                child.measure(MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(child.getMeasuredHeight(), MeasureSpec.EXACTLY));
            }
            flexLine.mainSize += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        } else {
            // The direction of main axis is vertical
            if (!mChildrenFrozen[childIndex]) {
                float rawCalculatedHeight = child.getMeasuredHeight() - unitShrink * lp.flexShrink;
                if (i == flexLine.itemCount - 1) {
                    rawCalculatedHeight += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newHeight = Math.round(rawCalculatedHeight);
                if (newHeight < lp.minHeight) {
                    // Need to invoke this method again like the case flex direction is vertical
                    needsReshrink = true;
                    newHeight = lp.minHeight;
                    mChildrenFrozen[childIndex] = true;
                    flexLine.totalFlexShrink -= lp.flexShrink;
                } else {
                    accumulatedRoundError += (rawCalculatedHeight - newHeight);
                    if (accumulatedRoundError > 1.0) {
                        newHeight += 1;
                        accumulatedRoundError -= 1;
                    } else if (accumulatedRoundError < -1.0) {
                        newHeight -= 1;
                        accumulatedRoundError += 1;
                    }
                }
                child.measure(MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(), MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
            }
            flexLine.mainSize += child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
        }
        childIndex++;
    }

    if (needsReshrink && sizeBeforeShrink != flexLine.mainSize) {
        // Re-invoke the method with the same startIndex to distribute the negative free space
        // that wasn't fully distributed (because some views length were not enough)
        shrinkFlexItems(flexLine, flexDirection, maxMainSize, paddingAlongMainAxis, startIndex);
    }
    return childIndex;
}

From source file:com.devabit.takestock.ui.widget.FlexboxLayout.java

/**
 * Expand the flex items along the main axis based on the individual flexGrow attribute.
 *
 * @param flexLine             the flex line to which flex items belong
 * @param flexDirection        the flexDirection value for this FlexboxLayout
 * @param maxMainSize          the maximum main size. Expanded main size will be this size
 * @param paddingAlongMainAxis the padding value along the main axis
 * @param startIndex           the start index of the children views to be expanded. This index
 *                             needs to//from  www  .ja v  a 2 s . c o m
 *                             be an absolute index in the flex container (FlexboxLayout),
 *                             not the relative index in the flex line.
 * @return the next index, the next flex line's first flex item starts from the returned index
 * @see #getFlexDirection()
 * @see #setFlexDirection(int)
 * @see LayoutParams#flexGrow
 */
private int expandFlexItems(FlexLine flexLine, @FlexDirection int flexDirection, int maxMainSize,
        int paddingAlongMainAxis, int startIndex) {
    int childIndex = startIndex;
    if (flexLine.totalFlexGrow <= 0 || maxMainSize < flexLine.mainSize) {
        childIndex += flexLine.itemCount;
        return childIndex;
    }
    int sizeBeforeExpand = flexLine.mainSize;
    boolean needsReexpand = false;
    float unitSpace = (maxMainSize - flexLine.mainSize) / flexLine.totalFlexGrow;
    flexLine.mainSize = paddingAlongMainAxis;
    float accumulatedRoundError = 0;
    for (int i = 0; i < flexLine.itemCount; i++) {
        View child = getReorderedChildAt(childIndex);
        if (child == null) {
            continue;
        } else if (child.getVisibility() == View.GONE) {
            childIndex++;
            continue;
        }
        LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (flexDirection == FLEX_DIRECTION_ROW || flexDirection == FLEX_DIRECTION_ROW_REVERSE) {
            // The direction of the main axis is horizontal
            if (!mChildrenFrozen[childIndex]) {
                float rawCalculatedWidth = child.getMeasuredWidth() + unitSpace * lp.flexGrow;
                if (i == flexLine.itemCount - 1) {
                    rawCalculatedWidth += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newWidth = Math.round(rawCalculatedWidth);
                if (newWidth > lp.maxWidth) {
                    // This means the child can't expand beyond the value of the maxWidth attribute.
                    // To adjust the flex line length to the size of maxMainSize, remaining
                    // positive free space needs to be re-distributed to other flex items
                    // (children views). In that case, invoke this method again with the same
                    // startIndex.
                    needsReexpand = true;
                    newWidth = lp.maxWidth;
                    mChildrenFrozen[childIndex] = true;
                    flexLine.totalFlexGrow -= lp.flexGrow;
                } else {
                    accumulatedRoundError += (rawCalculatedWidth - newWidth);
                    if (accumulatedRoundError > 1.0) {
                        newWidth += 1;
                        accumulatedRoundError -= 1.0;
                    } else if (accumulatedRoundError < -1.0) {
                        newWidth -= 1;
                        accumulatedRoundError += 1.0;
                    }
                }
                child.measure(MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(child.getMeasuredHeight(), MeasureSpec.EXACTLY));
            }
            flexLine.mainSize += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        } else {
            // The direction of the main axis is vertical
            if (!mChildrenFrozen[childIndex]) {
                float rawCalculatedHeight = child.getMeasuredHeight() + unitSpace * lp.flexGrow;
                if (i == flexLine.itemCount - 1) {
                    rawCalculatedHeight += accumulatedRoundError;
                    accumulatedRoundError = 0;
                }
                int newHeight = Math.round(rawCalculatedHeight);
                if (newHeight > lp.maxHeight) {
                    // This means the child can't expand beyond the value of the maxHeight
                    // attribute.
                    // To adjust the flex line length to the size of maxMainSize, remaining
                    // positive free space needs to be re-distributed to other flex items
                    // (children views). In that case, invoke this method again with the same
                    // startIndex.
                    needsReexpand = true;
                    newHeight = lp.maxHeight;
                    mChildrenFrozen[childIndex] = true;
                    flexLine.totalFlexGrow -= lp.flexGrow;
                } else {
                    accumulatedRoundError += (rawCalculatedHeight - newHeight);
                    if (accumulatedRoundError > 1.0) {
                        newHeight += 1;
                        accumulatedRoundError -= 1.0;
                    } else if (accumulatedRoundError < -1.0) {
                        newHeight -= 1;
                        accumulatedRoundError += 1.0;
                    }
                }
                child.measure(MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(), MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY));
            }
            flexLine.mainSize += child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
        }
        childIndex++;
    }

    if (needsReexpand && sizeBeforeExpand != flexLine.mainSize) {
        // Re-invoke the method with the same startIndex to distribute the positive free space
        // that wasn't fully distributed (because of maximum length constraint)
        expandFlexItems(flexLine, flexDirection, maxMainSize, paddingAlongMainAxis, startIndex);
    }
    return childIndex;
}