Search code examples
androidapipopupwindowviewgrouponbackpressed

Disabling the back button for popup windows


Based on a YouTube tutorial video (https://www.youtube.com/watch?v=wxqgtEewdfo) that teaches how to create popup windows, I was wondering how to dismiss the popup with a touch event as opposed to the back button...

Here's MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RelativeLayout relative = (RelativeLayout)findViewById(R.id.relativeTest);

    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().
                    getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.myLayout, null);

            PopupWindow popupWindow = new PopupWindow(container, AbsListView.LayoutParams.MATCH_PARENT,
                    AbsListView.LayoutParams.MATCH_PARENT, true);
            popupWindow.showAtLocation(relative, Gravity.CENTER, 0, 0);

            container.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    popupWindow.dismiss();

                    return true;
                }
            });
        }
    });
}

@Override
public void onBackPressed() {
    // I want the back button to be disabled for both MainActivity and the
    // popup window.
}

... Should I place onBackPressed() elsewhere or would that even be possible?

Thanks in advance.


Solution

  • Ok, I figured it out (credits to Filip, the uploader of the YouTube video) now... The problem was that I included and set the last parameter of PopupWindow, focusable, to true, and as soon as I got rid of it as follows:

    popupWindow = new PopupWindow(container, AbsListView.LayoutParams.MATCH_PARENT,
                        AbsListView.LayoutParams.MATCH_PARENT);
    

    ... The popup is now only dismissable by a touch event.