[英]How to get or compute the width/height of an inflated view
如果父級是PopupWindow而不是ViewGroup,如何計算膨脹視圖的寬度和高度? 我不能使用LayoutInflator.inflate(int resId, ViewGroup parent, attachToRoot boolean)
因為PopupWindow不是ViewGroup,所以我使用LayoutInflator.inflate(int resId)
代替,但之后我getWidth()和getHeight()返回零:(
我需要調整PopupWindow的大小以適應View,但是在View有父級之前不能這樣做。 我有雞蛋問題嗎?
順便說一句,View是RelativeView的子類,因此手動計算它基本上是不可能的。
先謝謝你,巴里
實際上popupWindow支持“包裝內容”constans,所以如果你想要彈出窗口就像你的視圖一樣 - 使用這個:
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()
方法 - 將測量所有子項和視圖本身,並且您可以獲取view.getMeasuredHeight()
和view.getMeasuredWidth()
。
正如Jin35所說,你的問題是視圖的寬度和高度尚未計算......尺寸直到布局通過后才計算出來。
使用來自維度資源的固定寬度和高度(例如,來自值/ 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);
}
}
});
}
}
請試試這個:
Display display = getWindowManager().getDefaultDisplay();
Log.e("", "" + display.getHeight() + " " + display.getWidth());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.