dismiss the popup window by back button

please write onBackPressed() and have following code

if(popup!=null){
   //dismiss the popup
   popup.dismiss();
   //make popup null again
   popup=null;
}

Maintain global reference for PopUpWindow and override onBackPressed()...

@Override
public void onBackPressed() {
    if (popupWindow != null && popupWindow.isShowing()) {
        popupWindow.dismiss();
    } else {
        super.onBackPressed();
    }
}

To dismiss by the same Button...

    ivmainmenu.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if(popupWindow != null && popupWindow.isShowing()) {
                popupWindow.dismiss();
                popupWindow = null;
            } else {
                // show pop up now
            }
        }
    });

Replace

popupWindow.setOutsideTouchable(false);

with this

popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);