PopupWindow is different from our Activity, because when we construct PWs, we often do not inherit from them, but from new. Therefore, methods such as onKeyDown() overriding PW cannot be used to intercept keyboard events. Fortunately, the characteristics of PW itself make it easy for us to exit with the return key. Of course, we can also intercept keyboard events, so there are two ways.
Method 1: The easiest method
When new, use the following method:
popupWindow = new PopupWindow(popupWindow_view, 200, 150, true);
The key lies in the last parameter. The prompt given by the SDK is Focusable, as the name implies, it is the Focusable property of the PW, so that it can accept focus.
Of course you can use another constructor and then manually set the focusable property:
(true); // Generally, the components in popupWindow need to be focused, and are often used to receive user input or actions.
Note: The following line of statements with unknown functions must be added to work:
(newBitmapDrawable());// Response returns the key required statement.
Rest assured that setting BackgroundDrawable will not change the background color or image you set in the configuration file.
Method 2: The most general method
First, select a view that does not affect any operation in the PW layout file (*.xml). It is recommended to use the outermost layer of Layout. Then set the Focusable and FocusableInTouchMode of the Layout to true. Then go back to the code and get an instance of the View, and now you can rewrite the OnKeyListener() event for the View. We can manually capture KEYCODE_BACK to the dialog box dismiss(). Give an example:
privatePopupWindow pw;
privateView view;
privateLinearLayout layMenu;
LayoutInflater inflater = (LayoutInflater) (Context.LAYOUT_INFLATER_SERVICE);
view = (.popup_main_menu,null, false);
layMenu = (LinearLayout) ();
pw =new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
(newOnKeyListener()
{
publicboolean onKey(View v, intkeyCode, KeyEvent event)
{
if(() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK)
();
returnfalse;
}
});
The codes of the above two methods can coexist. Of course, if you use the first method, you don't need to capture the return key anymore, but you can try to capture other keys you need.