Calculates the height and sets it for views with wrap_content as height. - Android User Interface

Android examples for User Interface:View Size

Description

Calculates the height and sets it for views with wrap_content as height.

Demo Code


//package com.java2s;
import android.app.Activity;

import android.util.DisplayMetrics;
import android.view.View;

public class Main {
    /**/*from   w  w  w.j  ava 2s .  com*/
     * Calculates the height and sets it for views with wrap_content as height.
     */
    public static void setHeightForWrapContent(Activity activity, View view) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int screenWidth = metrics.widthPixels;

        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(
                screenWidth, View.MeasureSpec.EXACTLY);

        view.measure(widthMeasureSpec, heightMeasureSpec);
        int height = view.getMeasuredHeight();
        view.getLayoutParams().height = height;
    }
}

Related Tutorials