调试以下Android代码,弹出窗口

时间:2012-01-10 03:19:32

标签: android popup

public class Offer_Popup extends Activity {


 public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.offer_popup);

        //newly added code, the window popup
     LayoutInflater inflater = (LayoutInflater)
                   this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      PopupWindow pw = new PopupWindow(
                   inflater.inflate(R.layout.popup_example, null, false), 
                   100, 
                   100, 
                   true);

     pw.showAtLocation(this.findViewById(R.id.relativeLayout_popup), Gravity.CENTER, 0, 0);}       
            /////////////////////

popup_example.xml

     <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dip"
    android:text="Test Pop-Up"
  />

</LinearLayout>

DDMS显示最后一行showAtLocation是错误 它说无法添加窗口 - 令牌null无效。 android.view.WindowManagerBadToken。 在添加弹出窗口之前,程序运行正常。但在弹出代码之后,它崩溃了。什么是它正在谈论的坏标记?

2 个答案:

答案 0 :(得分:1)

弹出窗口需要一个初始窗口才能弹出。有人会认为一个Activity自动有一个Window,但从一开始就不是这样。在onAttachedToWindow()之前,给定的Activity没有活动窗口。此时,您可以将PopupWindow添加到窗口,因为存在一个窗口。

如果您将代码移动到onAttachedToWindow(),它应该按预期工作或者至少完全给您一个不同的错误。

希望这有帮助,

FuzzicalLogic

答案 1 :(得分:0)

您确定“popup_example”在布局文件中是否存在并且已正确定义?

请仔细检查文件。并在“膨胀”之后仔细检查pw的值。