【问题标题】:getHeight() of Non Inflated Custom View returns 0非膨胀自定义视图的 getHeight() 返回 0
【发布时间】:2019-05-14 08:29:43
【问题描述】:

我想要的是将视图转换为我需要根视图的高度和宽度的位图。 getMeasuredHeight 和 getMeasuredWidth 正在返回 0,通过 View 有效但不返回高度和宽度,

我怎样才能在不膨胀自定义 View 类的情况下获得有效的高度和宽度,只使用自定义视图对象的 java 实例。

我正在使用以下片段来获取视图的高度和宽度:

/**
     * Return the width of view.
     *
     * @param view The view.
     * @return the width of view
     */
    public static int getMeasuredWidth(final View view) {
        return measureView(view)[0];
    }

    /**
     * Return the height of view.
     *
     * @param view The view.
     * @return the height of view
     */
    public static int getMeasuredHeight(final View view) {
        return measureView(view)[1];
    }

    /**
     * Measure the view.
     *
     * @param view The view.
     * @return arr[0]: view's width, arr[1]: view's height
     */
    public static int[] measureView(final View view) {
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        if (lp == null) {
            lp = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
        }
        int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width);
        int lpHeight = lp.height;
        int heightSpec;
        if (lpHeight > 0) {
            heightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY);
        } else {
            heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        }
        view.measure(widthSpec, heightSpec);
        return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()};
    }

【问题讨论】:

    标签: android android-layout android-custom-view android-bitmap


    【解决方案1】:

    直到视图被膨胀和绘制后,尺寸属性才会被填充。获取属性的唯一方法是硬编码值,如果尺寸不是WRAP_CONTENT 或MATCH_PARENT,则从View.LayoutParams 获取尺寸,或者在活动中的onCreate() 或onViewCreated() 之后获取这些属性一个片段。

    如果您想将视图转换为位图,您可以在屏幕上绘制该视图(它可能对用户不可见)并从那里继续。

    【讨论】:

    • 我想将我的自定义视图打印为位图,但没有必要每次都在某些布局上绘制视图,有什么方法可以在临时布局上绘制并获得我的视图高度和宽度?
    • 是的,不幸的是,您必须绘制视图才能打印它/截屏。您可以在用户暂时不注意的情况下绘制它,并在完成后立即将其删除。视图有什么特殊的东西还是只是一个位图图像?因为在这种情况下,您最好单独操作位图而不是绘制它。
    • 你能告诉我怎么做,或者指出任何例子吗?
    • 请记住,如果您对尺寸进行硬编码(它们也可能与屏幕尺寸相关),您可以做任何您想做的事情。
    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多