Reputation: 7947
I need to use a popup window from within a sub thread. Looking around at various snippets of example code, I have arrived at the following:
void completed_dialog()
{
dialog_action_taken = false;
runOnUiThread(new Runnable()
{
public void run()
{
Button but = (Button) findViewById(R.id.pop_can);
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.endofgame,
null, false), 300, 300, true);
pw.setBackgroundDrawable(new BitmapDrawable());
OnClickListener cancel_button_click_listener = new OnClickListener()
{
public void onClick(View v)
{
pw.dismiss();
}
};
but.setOnClickListener(cancel_button_click_listener);
pw.showAtLocation(game_frame_layout, Gravity.CENTER, 0, 0);
}
}
}
If the line "but.setOnClickListener(cancel_button_click_listener);" is commented out then I see the dialog and the button perfectly. But if I leave the line in, then the program crashes at the point where the dialog is supposed to appear - i.e. I never see the dialog. Can I make the code work with just a small modification?
Upvotes: 1
Views: 422
Reputation: 63955
It's your findViewById()
that does not find the button. You need to have it look inside the layout like so
public void run()
{
LayoutInflater inflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.endofgame, null, false);
Button but = (Button) layout.findViewById(R.id.pop_can);
final PopupWindow pw = new PopupWindow(layout, 300, 300, true);
pw.setBackgroundDrawable(new BitmapDrawable());
OnClickListener cancel_button_click_listener = new OnClickListener()
{
public void onClick(View v)
{
pw.dismiss();
}
};
but.setOnClickListener(cancel_button_click_listener);
pw.showAtLocation(game_frame_layout, Gravity.CENTER, 0, 0);
}
Upvotes: 3