Android 如何获取或计算膨胀视图的宽度/高度

Android 如何获取或计算膨胀视图的宽度/高度,android,Android,如果父视图是PopupWindow而不是视图组,如何计算膨胀视图的宽度和高度?我不能使用LayoutInflator.inflate(int-resId,ViewGroup-parent,attachToRoot-boolean)因为PopupWindow不是一个视图组,所以我使用LayoutInflator.inflate(int-resId),但在这之后,我的getWidth()和getHeight()返回零:( 我需要调整弹出窗口的大小以适应视图,但在视图有父视图之前不能这样做。我有鸡和蛋

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

我需要调整弹出窗口的大小以适应视图,但在视图有父视图之前不能这样做。我有鸡和蛋的问题吗

顺便说一下,视图是RelativeView的一个子类,因此手动计算它基本上是不可能的

提前感谢,, 巴里请试试这个:

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

实际上,popupWindow支持“包装内容”常量,因此如果您希望弹出窗口与视图完全一致,请使用以下命令:

popup = new PopupWindow(context);
popup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
--其他选项--

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

如果有
fill\u parent
值-您处于鸡蛋鸡的情况

如果
px
dp
中有值,则可以手动计算像素大小:

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

如果有
wrap\u content
value-您可以使用
view.measure()
方法-所有子项和视图本身都将被测量,您可以获得
view.getmeasuredeheight()
view.getmeasuredewidth()

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

从维度资源(例如,从values/dimens.xml文件)使用固定的宽度和高度是一种解决方法,因为这样您就不需要等待视图的onMeasure出现——您可以获得您感兴趣的视图所使用的相同维度资源的值,并使用它

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

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);
                }
            }
        });
    }
}

我需要的是视图的宽度和高度,而不是显示。这并不能回答OPYes的问题。我使用的是填充父对象。我最终使用了PopupWindow大小的计算值(显示宽度-填充)。它工作得很好。调用
LayoutInflator.inflate后,您能获得视图的尺寸吗(int-resId、视图组父对象、attachToRoot布尔值)