Egos Zhang
Egos Zhang

Reputation: 1354

PopupWindow - Dismiss when clicked back but not outside

I want to clicked back button to dismiss PopupWindow.But I can also click outside to do another thing,the PopupWindow don't miss. I try popupWindow.setFocusable(true);,but the PopupWindow will dismiss when I click outside. I try to custom view.

public class OtherBrifeIntroView extends LinearLayout
{
@Override
    public boolean dispatchKeyEvent(KeyEvent event)
    {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
        {
            Toast.makeText(mContext, "test", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

}

but it doesn't work.Can you help me?

Upvotes: 3

Views: 2114

Answers (2)

Egos Zhang
Egos Zhang

Reputation: 1354

I solve it.Set TouchModal false,but the setTouchModal is hide,so I use reflect.

public static void setPopupWindowTouchModal(PopupWindow popupWindow, boolean touchModal)
    {
        if (null == popupWindow)
        {
            return;
        }
        Method method;
        try
        {
            method = PopupWindow.class.getDeclaredMethod("setTouchModal", boolean.class);
            method.setAccessible(true);
            method.invoke(popupWindow, touchModal);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

Finally.

setPopupWindowTouchModal(popupWindow, false);
popupWindow.setFocusable(true);

Upvotes: 3

vguzzi
vguzzi

Reputation: 2428

You can call popupWindow.dismiss() to manually dismiss the PopupWindow within your dispatchKeyEvent method. In order to stop it dismissing when you touch outside of the PopupWindow there are a number of things you can try.

popupWindow.setOutsideTouchable(true);
popupWindow.setTouchable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable()); 

Have a play about with the above values and see what the outcome is, I am not on my developer computer at the moment so can't test which one it is.

Upvotes: 0

Related Questions