Set the size of ViewGroup by background image resource. - Android User Interface

Android examples for User Interface:ViewGroup

Description

Set the size of ViewGroup by background image resource.

Demo Code


//package com.java2s;

import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;

public class Main {
    /**//  w w  w . j  a v a2  s  .co m
     * Set the size of ViewGroup by background image resource.
     * @param parent
     */
    public static void setSizeBybackgroundImage(ViewGroup parent) {
        measureView(parent);
        ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) parent
                .getLayoutParams();
        lp.width = parent.getMeasuredWidth();
        lp.height = parent.getMeasuredHeight();
        parent.setLayoutParams(lp);
    }

    /**
     * Measure a view.
     * @param child
     */
    public static void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, 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);
    }
}

Related Tutorials