【问题标题】:How to get or compute the width/height of an inflated view如何获取或计算膨胀视图的宽度/高度
【发布时间】:2023-03-15 23:14:01
【问题描述】:

如果父级是 PopupWindow 而不是 ViewGroup,我如何计算膨胀视图的宽度和高度?我不能使用LayoutInflator.inflate(int resId, ViewGroup parent, attachToRoot boolean),因为 PopupWindow 不是 ViewGroup,所以我改用LayoutInflator.inflate(int resId),但之后我 getWidth() 和 getHeight() 返回零:(

我需要调整 PopupWindow 的大小以适应视图,但在视图有父视图之前不能这样做。我有先有鸡还是先有蛋的问题吗?

顺便说一句,View 是 RelativeView 的子类,因此手动计算它基本上是不可能的。

提前致谢, 巴里

【问题讨论】:

  • 调用LayoutInflator.inflate(int resId, ViewGroup parent, attachToRoot boolean)后你能得到你的View的尺寸吗?

标签: android


【解决方案1】:

实际上 popupWindow 支持“包装内容”常量,因此如果您希望弹出窗口与您的视图完全相同 - 使用这个:

popup = new PopupWindow(context);
popup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

--其他选项--

getWidth() 和 getHeight() 返回零,因为视图只有在屏幕上绘制后才有大小。您可以尝试从膨胀视图的LayoutParams 获取值。

如果有fill_parent 值 - 你处于鸡蛋鸡的情况。

如果px 或dp 中有值,您可以手动计算大小(以像素为单位):

Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpSize, context.getResources().getDisplayMetrics()));

如果有wrap_content值——你可以使用view.measure()方法——所有的children和view本身都会被测量,你可以得到view.getMeasuredHeight()和view.getMeasuredWidth()。

【讨论】:

  • 是的,我正在使用 fill_parent。我最终使用了 PopupWindow 大小的计算值(显示宽度 - 填充)。它工作得很好。
【解决方案2】:

正如 Jin35 所说,您的问题是尚未计算视图的宽度和高度...直到布局通过后才计算尺寸。

使用来自维度资源(例如来自 values/dimens.xml 文件)的固定宽度和高度是一种解决方法,因为那时您无需等待视图的 onMeasure 发生 - 您可以获得用于您感兴趣的视图的相同维度资源,并使用它。

更好的解决方案是将计算延迟到 onMeasure 发生之后。您可以通过覆盖 onMeasure 来做到这一点,但更优雅的解决方案是使用临时 OnGlobalLayoutListener,如下所示:

View popup = LayoutInflator.inflate(int resId);
if(popup != null) {

    // set up an observer that will be called once the listView's layout is ready
    android.view.ViewTreeObserver viewTreeObserver = listView.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {

        viewTreeObserver.addOnGlobalLayoutListener(new android.view.ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                // This will be called once the layout is finished, prior to displaying.

                View popup = findViewById(resId);

                if(popup != null) {
                    int width = popup.getMeasuredWidth();
                    int height = popup.getMeasuredHeight();

                    // don't need the listener any more
                    popup.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
            }
        });
    }
}

【讨论】:

    【解决方案3】:

    请试试这个:

    Display display = getWindowManager().getDefaultDisplay();
    Log.e("", "" + display.getHeight() + " " + display.getWidth());
    

    【讨论】:

    • 我需要 View 的宽度和高度,而不是显示。
    • 这不回答OP的问题
    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 2017-06-26
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2011-03-28
    相关资源
    最近更新 更多