create Child View Width Measure Spec - Android User Interface

Android examples for User Interface:View Size

Description

create Child View Width Measure Spec

Demo Code


//package com.java2s;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.LinearLayout.LayoutParams;

public class Main {

    public static int createChildWidthMeasureSpec(
            int parentWidthMeasureSpec, View view) {
        // ? View ?
        int parentWidthMode = MeasureSpec.getMode(parentWidthMeasureSpec);
        // ? View 
        int parentWidthSize = MeasureSpec.getSize(parentWidthMeasureSpec);

        //  View ?
        int childWidthMeasureSpec = 0;

        // ? View  LayoutParams
        LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();

        if (parentWidthMode == MeasureSpec.EXACTLY) {
            /*  dp ? */
            if (layoutParams.width > 0) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        layoutParams.width, MeasureSpec.EXACTLY);
            } else if (layoutParams.width == LayoutParams.WRAP_CONTENT) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        parentWidthSize, MeasureSpec.AT_MOST);
            } else if (layoutParams.width == LayoutParams.MATCH_PARENT) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        parentWidthSize, MeasureSpec.EXACTLY);
            }//from   ww w  .j  a v  a2 s.  c  o  m
        } else if (parentWidthMode == MeasureSpec.AT_MOST) {
            /*  WRAP_CONTENT ? */
            if (layoutParams.width > 0) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        layoutParams.width, MeasureSpec.EXACTLY);
            } else if (layoutParams.width == LayoutParams.WRAP_CONTENT) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        parentWidthSize, MeasureSpec.AT_MOST);
            } else if (layoutParams.width == LayoutParams.MATCH_PARENT) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        parentWidthSize, MeasureSpec.EXACTLY);
            }
        } else if (parentWidthMode == MeasureSpec.UNSPECIFIED) {
            /*  MATCH_PARENT ? */
            if (layoutParams.width > 0) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        layoutParams.width, MeasureSpec.EXACTLY);
            } else if (layoutParams.width == LayoutParams.WRAP_CONTENT) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                        MeasureSpec.UNSPECIFIED);
            } else if (layoutParams.width == LayoutParams.MATCH_PARENT) {
                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                        MeasureSpec.UNSPECIFIED);
            }
        }

        //  View ?
        return childWidthMeasureSpec;
    }
}

Related Tutorials