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:android.support.percent.PercentLayoutHelper.java

/**
 * Iterates over children and checks if any of them would like to get more space than it
 * received through the percentage dimension.
 *
 * If you are building a layout that supports percentage dimensions you are encouraged to take
 * advantage of this method. The developer should be able to specify that a child should be
 * remeasured by adding normal dimension attribute with {@code wrap_content} value. For example
 * he might specify child's attributes as {@code app:layout_widthPercent="60%p"} and
 * {@code android:layout_width="wrap_content"}. In this case if the child receives too little
 * space, it will be remeasured with width set to {@code WRAP_CONTENT}.
 *
 * @return True if the measure phase needs to be rerun because one of the children would like
 * to receive more space.//from  w ww.  j  a  v  a 2 s .c om
 */
public boolean handleMeasuredStateTooSmall() {
    boolean needsSecondMeasure = false;
    for (int i = 0, N = mHost.getChildCount(); i < N; i++) {
        View view = mHost.getChildAt(i);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (DEBUG) {
            Log.d(TAG, "should handle measured state too small " + view + " " + params);
        }
        if (params instanceof PercentLayoutParams) {
            PercentLayoutInfo info = ((PercentLayoutParams) params).getPercentLayoutInfo();
            if (info != null) {
                if (shouldHandleMeasuredWidthTooSmall(view, info)) {
                    needsSecondMeasure = true;
                    params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
                if (shouldHandleMeasuredHeightTooSmall(view, info)) {
                    needsSecondMeasure = true;
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                }
            }
        }
    }
    if (DEBUG) {
        Log.d(TAG, "should trigger second measure pass: " + needsSecondMeasure);
    }
    return needsSecondMeasure;
}

From source file:android.support.design.internal.BottomNavigationMenuView.java

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = MeasureSpec.getSize(widthMeasureSpec);
    final int count = getChildCount();

    final int heightSpec = MeasureSpec.makeMeasureSpec(mItemHeight, MeasureSpec.EXACTLY);

    if (mShiftingMode) {
        final int inactiveCount = count - 1;
        final int activeMaxAvailable = width - inactiveCount * mInactiveItemMinWidth;
        final int activeWidth = Math.min(activeMaxAvailable, mActiveItemMaxWidth);
        final int inactiveMaxAvailable = (width - activeWidth) / inactiveCount;
        final int inactiveWidth = Math.min(inactiveMaxAvailable, mInactiveItemMaxWidth);
        int extra = width - activeWidth - inactiveWidth * inactiveCount;
        for (int i = 0; i < count; i++) {
            mTempChildWidths[i] = (i == mSelectedItemPosition) ? activeWidth : inactiveWidth;
            if (extra > 0) {
                mTempChildWidths[i]++;// ww  w. j  a  v  a2 s. c o m
                extra--;
            }
        }
    } else {
        final int maxAvailable = width / (count == 0 ? 1 : count);
        final int childWidth = Math.min(maxAvailable, mActiveItemMaxWidth);
        int extra = width - childWidth * count;
        for (int i = 0; i < count; i++) {
            mTempChildWidths[i] = childWidth;
            if (extra > 0) {
                mTempChildWidths[i]++;
                extra--;
            }
        }
    }

    int totalWidth = 0;
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() == GONE) {
            continue;
        }
        child.measure(MeasureSpec.makeMeasureSpec(mTempChildWidths[i], MeasureSpec.EXACTLY), heightSpec);
        LayoutParams params = child.getLayoutParams();
        params.width = child.getMeasuredWidth();
        totalWidth += child.getMeasuredWidth();
    }
    setMeasuredDimension(
            ViewCompat.resolveSizeAndState(totalWidth,
                    MeasureSpec.makeMeasureSpec(totalWidth, MeasureSpec.EXACTLY), 0),
            ViewCompat.resolveSizeAndState(mItemHeight, heightSpec, 0));
}

From source file:com.ibm.techathon.elven.smartpool.cards.SuggestedCard.java

@Override
public void setupInnerViewElements(ViewGroup parent, View viewImage) {
    if (viewImage != null) {

        if (parent != null && parent.getResources() != null) {
            DisplayMetrics metrics = parent.getResources().getDisplayMetrics();

            int base = 100;

            if (metrics != null) {
                viewImage.getLayoutParams().width = (int) (base * metrics.density);
                viewImage.getLayoutParams().height = (int) (base * metrics.density);
            } else {
                viewImage.getLayoutParams().width = 200;
                viewImage.getLayoutParams().height = 200;
            }/*from   w  ww  .ja  v  a 2s .  com*/
        }
    }
}

From source file:android.support.percent.PercentLayoutHelper.java

/**
 * Iterates over children and changes their width and height to one calculated from percentage
 * values.//from  w ww  . jav  a2 s  .  co  m
 * @param widthMeasureSpec Width MeasureSpec of the parent ViewGroup.
 * @param heightMeasureSpec Height MeasureSpec of the parent ViewGroup.
 */
public void adjustChildren(int widthMeasureSpec, int heightMeasureSpec) {
    if (DEBUG) {
        Log.d(TAG,
                "adjustChildren: " + mHost + " widthMeasureSpec: " + View.MeasureSpec.toString(widthMeasureSpec)
                        + " heightMeasureSpec: " + View.MeasureSpec.toString(heightMeasureSpec));
    }

    // Calculate available space, accounting for host's paddings
    int widthHint = View.MeasureSpec.getSize(widthMeasureSpec) - mHost.getPaddingLeft()
            - mHost.getPaddingRight();
    int heightHint = View.MeasureSpec.getSize(heightMeasureSpec) - mHost.getPaddingTop()
            - mHost.getPaddingBottom();
    for (int i = 0, N = mHost.getChildCount(); i < N; i++) {
        View view = mHost.getChildAt(i);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (DEBUG) {
            Log.d(TAG, "should adjust " + view + " " + params);
        }
        if (params instanceof PercentLayoutParams) {
            PercentLayoutInfo info = ((PercentLayoutParams) params).getPercentLayoutInfo();
            if (DEBUG) {
                Log.d(TAG, "using " + info);
            }
            if (info != null) {
                if (params instanceof ViewGroup.MarginLayoutParams) {
                    info.fillMarginLayoutParams(view, (ViewGroup.MarginLayoutParams) params, widthHint,
                            heightHint);
                } else {
                    info.fillLayoutParams(params, widthHint, heightHint);
                }
            }
        }
    }
}

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

@Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);

    final View tabContainer = mTabContainer;
    final boolean hasTabs = tabContainer != null && tabContainer.getVisibility() != GONE;

    if (tabContainer != null && tabContainer.getVisibility() != GONE) {
        final int containerHeight = getMeasuredHeight();
        final LayoutParams lp = (LayoutParams) tabContainer.getLayoutParams();
        final int tabHeight = tabContainer.getMeasuredHeight();
        tabContainer.layout(l, containerHeight - tabHeight - lp.bottomMargin, r,
                containerHeight - lp.bottomMargin);
    }/*from  www.  ja v  a2 s.c om*/

    boolean needsInvalidate = false;
    if (mIsSplit) {
        if (mSplitBackground != null) {
            mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
            needsInvalidate = true;
        }
    } else {
        if (mBackground != null) {
            if (mActionBarView.getVisibility() == View.VISIBLE) {
                mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(),
                        mActionBarView.getRight(), mActionBarView.getBottom());
            } else if (mContextView != null && mContextView.getVisibility() == View.VISIBLE) {
                mBackground.setBounds(mContextView.getLeft(), mContextView.getTop(), mContextView.getRight(),
                        mContextView.getBottom());
            } else {
                mBackground.setBounds(0, 0, 0, 0);
            }
            needsInvalidate = true;
        }
        mIsStacked = hasTabs;
        if (hasTabs && mStackedBackground != null) {
            mStackedBackground.setBounds(tabContainer.getLeft(), tabContainer.getTop(), tabContainer.getRight(),
                    tabContainer.getBottom());
            needsInvalidate = true;
        }
    }

    if (needsInvalidate) {
        invalidate();
    }
}

From source file:com.ryan.ryanreader.fragments.ImageViewFragment.java

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    final Context context = inflater.getContext();

    final LoadingView loadingView = new LoadingView(context, R.string.download_loading, true, false);

    final LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(loadingView);//from   w ww . j a  v a  2  s.  c o  m

    CacheManager.getInstance(context)
            .makeRequest(new CacheRequest(url, RedditAccountManager.getAnon(), null,
                    Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                    Constants.FileType.IMAGE, false, false, false, context) {

                private void setContentView(View v) {
                    layout.removeAllViews();
                    layout.addView(v);
                    v.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                    v.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                }

                @Override
                protected void onCallbackException(Throwable t) {
                    BugReportActivity.handleGlobalError(context.getApplicationContext(),
                            new RRError(null, null, t));
                }

                @Override
                protected void onDownloadNecessary() {
                    loadingView.setIndeterminate(R.string.download_waiting);
                }

                @Override
                protected void onDownloadStarted() {
                    loadingView.setIndeterminate(R.string.download_downloading);
                }

                @Override
                protected void onFailure(final RequestFailureType type, Throwable t, StatusLine status,
                        final String readableMessage) {

                    loadingView.setDone(R.string.download_failed);
                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status);

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {
                            // TODO handle properly
                            layout.addView(new ErrorView(getSupportActivity(), error));
                        }
                    });
                }

                @Override
                protected void onProgress(long bytesRead, long totalBytes) {
                    loadingView.setProgress(R.string.download_downloading,
                            (float) ((double) bytesRead / (double) totalBytes));
                }

                @Override
                protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, long timestamp,
                        UUID session, boolean fromCache, final String mimetype) {

                    if (mimetype == null || !Constants.Mime.isImage(mimetype)) {
                        revertToWeb();
                        return;
                    }

                    if (Constants.Mime.isImageGif(mimetype)) {

                        try {

                            gifThread = new GifDecoderThread(cacheFile.getInputStream(),
                                    new GifDecoderThread.OnGifLoadedListener() {

                                        public void onGifLoaded() {
                                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                                public void run() {
                                                    imageView = new ImageView(context);
                                                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                                    setContentView(imageView);
                                                    gifThread.setView(imageView);

                                                    imageView.setOnClickListener(new View.OnClickListener() {
                                                        public void onClick(View v) {
                                                            getSupportActivity().finish();
                                                        }
                                                    });
                                                }
                                            });
                                        }

                                        public void onOutOfMemory() {
                                            General.quickToast(context, R.string.imageview_oom);
                                            revertToWeb();
                                        }

                                        public void onGifInvalid() {
                                            General.quickToast(context, R.string.imageview_invalid_gif);
                                            revertToWeb();
                                        }
                                    });

                            gifThread.start();

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                    } else {

                        final Bitmap finalResult;

                        try {

                            final int maxTextureSize = 2048;
                            final Bitmap imageOrig = BitmapFactory.decodeStream(cacheFile.getInputStream());

                            if (imageOrig == null) {
                                General.quickToast(context,
                                        "Couldn't load the image. Trying internal browser.");
                                revertToWeb();
                                return;
                            }

                            final int maxDim = Math.max(imageOrig.getWidth(), imageOrig.getHeight());

                            if (maxDim > maxTextureSize) {

                                imageOrig.recycle();

                                final double scaleFactorPowerOfTwo = Math
                                        .log((double) maxDim / (double) maxTextureSize) / Math.log(2);
                                final int scaleFactor = (int) Math
                                        .round(Math.pow(2, Math.ceil(scaleFactorPowerOfTwo)));

                                final BitmapFactory.Options options = new BitmapFactory.Options();
                                options.inSampleSize = scaleFactor;
                                finalResult = BitmapFactory.decodeStream(cacheFile.getInputStream(), null,
                                        options);
                            } else {
                                finalResult = imageOrig;
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e);

                        } catch (OutOfMemoryError e) {
                            General.quickToast(context, "Out of memory. Trying internal browser.");
                            revertToWeb();
                            return;
                        }

                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            public void run() {
                                imageView = new GestureImageView(context);
                                imageView.setImageBitmap(finalResult);
                                imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                                setContentView(imageView);

                                imageView.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        getSupportActivity().finish();
                                    }
                                });
                            }
                        });
                    }
                }
            });

    final RedditPost src_post = getArguments().getParcelable("post");
    final RedditPreparedPost post = src_post == null ? null
            : new RedditPreparedPost(context, CacheManager.getInstance(context), 0, src_post, -1, false,
                    new RedditSubreddit("/r/" + src_post.subreddit, src_post.subreddit, false), false, false,
                    false, RedditAccountManager.getInstance(context).getDefaultAccount());

    final FrameLayout outerFrame = new FrameLayout(context);
    outerFrame.addView(layout);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(context);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(context,
                new BezelSwipeOverlay.BezelSwipeListener() {

                    public boolean onSwipe(BezelSwipeOverlay.SwipeEdge edge) {

                        toolbarOverlay.setContents(
                                post.generateToolbar(context, ImageViewFragment.this, toolbarOverlay));
                        toolbarOverlay.show(edge == BezelSwipeOverlay.SwipeEdge.LEFT
                                ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

    }

    return outerFrame;
}

From source file:android.widget.PinnedHeaderListView.java

private void ensurePinnedHeaderLayout(final int viewIndex) {
    final View view = mHeaders[viewIndex].view;
    if (view.isLayoutRequested()) {
        final ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        int widthSpec;
        int heightSpec;

        if (layoutParams != null && layoutParams.width > 0)
            widthSpec = View.MeasureSpec.makeMeasureSpec(layoutParams.width, View.MeasureSpec.EXACTLY);
        else/* w  w  w. j a va  2  s.  c  o m*/
            widthSpec = View.MeasureSpec.makeMeasureSpec(mHeaderWidth, View.MeasureSpec.EXACTLY);

        if (layoutParams != null && layoutParams.height > 0)
            heightSpec = View.MeasureSpec.makeMeasureSpec(layoutParams.height, View.MeasureSpec.EXACTLY);
        else
            heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(widthSpec, heightSpec);
        final int height = view.getMeasuredHeight();
        mHeaders[viewIndex].height = height;
        view.layout(0, 0, view.getMeasuredWidth(), height);
    }
}

From source file:ca.barrenechea.widget.recyclerview.decoration.DoubleHeaderDecoration.java

private void measureView(RecyclerView parent, View header) {
    int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(), View.MeasureSpec.EXACTLY);
    int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(), View.MeasureSpec.UNSPECIFIED);

    int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
            parent.getPaddingLeft() + parent.getPaddingRight(), header.getLayoutParams().width);
    int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
            parent.getPaddingTop() + parent.getPaddingBottom(), header.getLayoutParams().height);

    header.measure(childWidth, childHeight);
    header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());
}

From source file:ca.barrenechea.widget.recyclerview.decoration.StickyHeaderDecoration.java

private RecyclerView.ViewHolder getHeader(RecyclerView parent, int position) {
    final long key = mAdapter.getHeaderId(position);

    if (mHeaderCache.containsKey(key)) {
        return mHeaderCache.get(key);
    } else {/*w w w. j  ava  2  s .  c  o m*/
        final RecyclerView.ViewHolder holder = mAdapter.onCreateHeaderViewHolder(parent);
        final View header = holder.itemView;

        //noinspection unchecked
        mAdapter.onBindHeaderViewHolder(holder, position);

        int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.EXACTLY);
        int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(),
                View.MeasureSpec.UNSPECIFIED);

        int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
                parent.getPaddingLeft() + parent.getPaddingRight(), header.getLayoutParams().width);
        int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
                parent.getPaddingTop() + parent.getPaddingBottom(), header.getLayoutParams().height);

        header.measure(childWidth, childHeight);
        header.layout(0, 0, header.getMeasuredWidth(), header.getMeasuredHeight());

        mHeaderCache.put(key, holder);

        return holder;
    }
}

From source file:com.actionbarsherlock.internal.widget.IcsListPopupWindow.java

private void measureScrapChild(View child, int position, int widthMeasureSpec) {
    ListView.LayoutParams p = (ListView.LayoutParams) child.getLayoutParams();
    if (p == null) {
        p = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                0);//from ww  w  . jav a2 s  .  c o  m
        child.setLayoutParams(p);
    }
    //XXX p.viewType = mAdapter.getItemViewType(position);
    //XXX p.forceAdd = true;

    int childWidthSpec = ViewGroup.getChildMeasureSpec(widthMeasureSpec,
            mDropDownList.getPaddingLeft() + mDropDownList.getPaddingRight(), p.width);
    int lpHeight = p.height;
    int childHeightSpec;
    if (lpHeight > 0) {
        childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
    } else {
        childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    }
    child.measure(childWidthSpec, childHeightSpec);
}