get Custom View width and height with MeasureSpec - Android User Interface

Android examples for User Interface:View Size

Description

get Custom View width and height with MeasureSpec

Demo Code


//package com.java2s;

import android.view.View.MeasureSpec;

public class Main {
    public static Integer[] getWHCustomView(int widthMeasureSpec,
            int heightMeasureSpec) {
        int desiredWidth = 100;
        int desiredHeight = 100;

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int width;
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;/*from  ww w. j  av a 2 s  .  c  o  m*/
        } else if (widthMode == MeasureSpec.AT_MOST) {
            width = Math.min(desiredWidth, widthSize);
        } else {
            width = desiredWidth;
        }

        int height;
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            height = Math.min(desiredHeight, heightSize);
        } else {
            height = desiredHeight;
        }

        Integer[] res = { width, height };
        return res;

    }
}

Related Tutorials