将自定义视图设置为Wrap_content

时间:2016-04-26 08:01:00

标签: android height width android-custom-view android-wrap-content

我正在使用库OnBarCodeGenerate for android。这会在自定义视图中绘制条形码。我应该如何编写自定义View的onMeasure方法,使其占用所需的空间。与wrap_content的高度和宽度相同。 ?

现在我的自定义视图的onMeasure方法如下。我必须给出所需的宽度。

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(),getMeasuredHeight());
        int desiredWidth = 200 * (int)getResolution();
        int desiredHeight = 200 * (int) getResolution();

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

        setMeasuredDimension(widthSize, heightSize);
        super.onMeasure(widthSize,heightSize);

        int width;
        int height;

        //Measure Width
        if (widthMode == MeasureSpec.EXACTLY) {
            //Must be this size
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...

            width = Math.min(desiredWidth, widthSize);
        } else {
            //Be whatever you want
            width = desiredWidth;
        }

        //Measure Height
        if (heightMode == MeasureSpec.EXACTLY) {
            //Must be this size
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            //Can't be bigger than...
            height = Math.min(desiredHeight, heightSize);
        } else {
            //Be whatever you want
            height = desiredHeight;
        }


        //MUST CALL THIS
        setMeasuredDimension(width,height);
    }

0 个答案:

没有答案