Search code examples
androidback-buttonkeylistenerpopupwindow

how to listen key when popup is opened


I am writing an application to animate popup window. It was working great with my code.

I want to close the popup window(i.e to slide-down it), when back button is pressed on device.

But I couldn't listen any one key from device. I used setOnKeyListener of that popup window, I didn't even get log from it.

My Code is given below:

popup_layout = layoutInflater.inflate(R.layout.popup_addchannel, null);
            popupWindow = new PopupWindow(popup_layout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
subscribeButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {

//                  Log.d(TAG,
//                          "Button is clicked for animation....  Visibility is"
//                                  + subscribeButton.getVisibility());
                    openMenu(view);
                }
            });
popup_layout.setOnKeyListener(new View.OnKeyListener() {

                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    Log.d(TAG, "on key button click called.........");
                    return false;
                }

            });

public void openMenu(View view) {
        if (!flag) {
            popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
            popupWindow.showAtLocation(view.findViewById(R.id.button1),
                    Gravity.CENTER, 0, 0);
            popupWindow.setFocusable(true);
            popupWindow.update();
            flag = true;
        } else {
            popupWindow.dismiss();
            popupWindow.setFocusable(false);
            flag = false;
        }
    }

What is the problem behind this?

Shall i achieve my requirement?

Please, Guide me.

Thank you in Advance!


Solution

  • try this....

        final PopupWindow popupWindow = new PopupWindow(popupView,
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
        ...
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupMenu.getContentView().setOnKeyListener(new View.OnKeyListener() {        
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode ==  KeyEvent.KEYCODE_MENU && 
                        event.getRepeatCount() == 0 && 
                        event.getAction() == KeyEvent.ACTION_DOWN) {
                    // ... payload action here. e.g. popupMenu.dismiss();
                    return true;
                }                
                return false;
            }
        });