的Android:弹出窗口和按钮关闭不工作

问题描述:

我:的Android:弹出窗口和按钮关闭不工作

popUp.xml

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

      .... 
    <Button 
     android:id="@+id/ok_button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="ok" 
     android:gravity="left" 
     /> 
</LinearLayout> 

main.java

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     ListView listView = (ListView)findViewById(R.id.list); 
    listView.setOnItemClickListener(new OnItemClickListener() 
       { 
       public void onItemClick(AdapterView<?> parent, View v, 
       int position, long id) 
       { 
        popUp();  

       } 
     }); 

,我得到强制关闭这里

public void popUp(){ 
      LayoutInflater inflater = (LayoutInflater) project.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      final PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup,null, false),300,400,true); 
      ok_button = (Button) findViewById(R.id.ok_button); 
      pw.showAtLocation(findViewById(R.id.list), Gravity.BOTTOM, 0,10); 
      ok_button.setOnClickListener(new OnClickListener() { //here I get FC 
       @Override 
       public void onClick(View v) { 

       pw.dismiss(); 

       } 
    }); 
     } 


    } 

当我使用按钮(在popUp();)从main.x毫升而不是popUp.xml一切正常。 什么是错的使用按钮从没有main.xml中

我觉得现在的问题是在这里:

ok_button = (Button) findViewById(R.id.ok_button); 

它正在寻找主要布局内的按钮来查看,而不是寻找弹出布局内。所以可能ok_button是空的。

尝试将充气呼叫从构造函数中搬出来,像这样:

View v = inflater.inflate(R.layout.popup,null, false); 
final PopupWindow pw = new PopupWindow(v,300,400,true); 

然后:

ok_button = (Button) v.findViewById(R.id.ok_button); 
+0

它的工作。谢谢。 – aptyp 2011-12-21 20:09:36