弹出视图没有显示出来?

10

以下是XML代码(仅为一个webview):

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/couponView" android:layout_height="100dp" android:layout_width="100dp" />

并且代码:

final View cView = getLayoutInflater().inflate(R.layout.couponlayout, null);
PopupWindow pw = new PopupWindow(cView);
pw.showAtLocation(findViewById(R.id.mainLayout), Gravity.CENTER, 100, 100);
pw.update();

这段代码在一个按钮的onClick()方法中。当我点击按钮时,其他应该发生的事情都发生了(按钮颜色、文本等改变),但是PopupWindow没有显示出来。我搜索了整个网络,但找不到任何解决方法。我做错了什么?

编辑:没人知道发生了什么吗?我感觉这是一个常见的问题。

2个回答

27
PopupWindow.setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

注意:setWindowLayoutMode已被弃用,请使用setHeight和setWidth。


+1 我一直在尝试找到一种使用Scott的答案而不必使用静态高度/宽度值的方法。这对我帮助很大! - mpellegr
2
转念一想,如果您使用此方法,popupwindows 的 getWidth() 和 getHeight() 方法将返回 0。相反,您可以从弹出窗口内部的视图中获取宽度和高度,并将其设置为弹出窗口的尺寸,以模拟 wrap_content。像这样:popupWindow.setContentView(myView); popupWindow.setHeight(myView.getHeight()); popupWindow.setWidth(myView.getWidth()); - mpellegr
1
setWindowLayoutMode已被弃用。现在他们希望你使用setHeight和setWidth。 - James andresakis
这个方法在API 23中已经被弃用了。http://developer.android.com/reference/android/widget/PopupWindow.html#setWindowLayoutMode(int, int) - Ian Wong

11
弹出窗口可能具有0的宽度和高度,因为未初始化尺寸,这就解释了为什么您看不到任何内容。您可以使用setHeightsetWidth设置高度和宽度,或者使用构造函数PopupWindow(View contentView, int width, int height)来完成。请参阅Androidreference获取更多信息。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接