0

I want to close the popup window when I click a button, but it seems dismiss function doesn't work and the window is not closing. What did I wrong?

(I'm a beginner, so codes might be 'weird'. Please understand...)

public class AlarmPopup extends Activity {
    private PopupWindow popup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        onShowPopup();
    }

    public void onShowPopup(){
        LayoutInflater inflater = (LayoutInflater)     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.alarm_popup, null, false);
        final PopupWindow popup = new PopupWindow(view, 400, 300, true);

        setContentView(R.layout.alarm_popup);

        view.findViewById(R.id.button).post(new Runnable() {
            @Override
            public void run() {
                popup.showAtLocation(view, Gravity.CENTER, 0, 0);
            }
        });

        findViewById(R.id.button).setOnClickListener(mClickListener);
    }

    Button.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) { // dismiss and stop the alarm function on other class
            Intent i = new Intent(AlarmPopup.this, AlarmService.class);
            stopService(i); // this function is working...
            popup.dismiss();
        }
    };
}
Laione
  • 25
  • 5

2 Answers2

0

You have declared popup as global and inside your onShowPopup you are creating new object for popup so that local popup will never be accessible from listener so make the changes as below:

public void onShowPopup(){
    LayoutInflater inflater = (LayoutInflater)     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View view = inflater.inflate(R.layout.alarm_popup, null, false);
    popup = new PopupWindow(view, 400, 300, true);

    setContentView(R.layout.alarm_popup);

    view.findViewById(R.id.button).post(new Runnable() {
        @Override
        public void run() {
            popup.showAtLocation(view, Gravity.CENTER, 0, 0);
        }
    });

    view.findViewById(R.id.button).setOnClickListener(mClickListener);
}
Rajesh Panchal
  • 1,140
  • 3
  • 20
  • 39
0

Popup variable that you are using to dismiss your popup window has not been initialized in the code that you have posted. Your final variable that you have created inside method is local and will not be accessible outside that method. So initialize your variable or use same variable inside method too.

Vivek Mishra
  • 5,669
  • 9
  • 46
  • 84