问题
I have:
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();
}
});
and I get force close here
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();
}
});
}
}
When I use button (in popUp();) from main.xml instead of popUp.xml everything is working. What is wrong with using the button from not main.xml
回答1:
I think that the problem is here:
ok_button = (Button) findViewById(R.id.ok_button);
it is looking for the button view inside the main layout instead of looking inside the popup layout. So probably ok_button is null.
Try to move out the inflate call from the constructor, like this:
View v = inflater.inflate(R.layout.popup,null, false);
final PopupWindow pw = new PopupWindow(v,300,400,true);
and then:
ok_button = (Button) v.findViewById(R.id.ok_button);
来源:https://stackoverflow.com/questions/8595427/android-popup-and-button-to-dismiss-doesnt-work