2013-07-22 60 views
6

我每次尝试启动窗口类时都会收到此错误。我使用单独的类,而不仅仅是我的游戏类中的方法,因为我需要禁用该弹出窗口上的后退按钮。我用一个按钮来调用这个类。如果我在游戏类中使用它,但不在单独的类中,此代码正常工作。这里是我的代码:

public class Popup_pogresno extends Activity implements OnClickListener{ 

    private PopupWindow pwindow; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 

     LayoutInflater layoutInflater 
     = (LayoutInflater)Popup_pogresno.this 
      .getSystemService(LAYOUT_INFLATER_SERVICE); 
     View popupView = layoutInflater.inflate(R.layout.popup, null); 
       pwindow = new PopupWindow(popupView, 300, 170, true); 

       Button btnDismiss = (Button)popupView.findViewById(R.id.bPopupOK); 
       btnDismiss.setOnClickListener(new Button.OnClickListener(){ 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      pwindow.dismiss(); 
     }}); 

       pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0); 

     } 

    public void onClick(View v) { 
     // TODO Auto-generated method stub 

    } 
    @Override 
    public void onBackPressed() { 

    } 
} 

回答

13

你是不是在你的onCreate(Bundle)方法调用setContentView(R.layout.myLayout)。在super.onCreate(savedInstanceState);之后立即致电。

这是从Android开发网站上的活动资源页面:

There are two methods almost all subclasses of Activity will implement:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

编辑1:

替换:

pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0); 

有:

new Handler().postDelayed(new Runnable(){ 

    public void run() { 
     pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0); 
    } 

}, 100L); 
+0

这是错误行:pwindow.showAtLocation(popupView,Gravity.CENTER,0,0); – marjanbaz

+0

@marjanbaz看到我上面的编辑。 – Vikram

+0

省略对'setContentView'的调用不是错误。在这种情况下,活动只会有一个空白的视图。这通常不太有用,但它也不会阻止显示弹出窗口。 – mrb

相关问题