Popupwindow is different from our activity, because we do not inherit the PW structure, but are new.
Therefore, you cannot use methods like onkeydown () to override PW to intercept Keyboard Events.
Fortunately, the features of PW make it easy for us to exit with the return key. Of course, we can also intercept Keyboard Events, so there are two methods.
Simplest --
When using new, use the following method:
1 |
New Popupwindow (view, layoutparams. wrap_content, layoutparams. wrap_content, True ); |
The key lies in the last parameter. The adk prompts focusable, as its name implies, that is, the PW's focusable attribute, so that it can accept the focus.
You can also set it manually:
12 |
PW. setfocusable ( True ); PW. setfocusableintouchmode ( True ); // Add this sentence for the sake of Insurance |
At this point, it still does not work. Baidu concluded that the following unknown statements must be added to play a role:
1 |
PW. setbackgrounddrawable ( New Bitmapdrawable ());
// Response to the required statement of the Return key |
Please rest assured that setting backgrounddrawable does not change the background color or image you set in the configuration file.
Most common --
First, select a view that does not affect any operation in the PW layout file (*. XML). We recommend that you use the outermost layout.
Set the focusable and focusableintouchmode of the layout to true.
Then returnCodeAnd now you can rewrite the onkeylistener () event on The View.
We can manually capture keycode_back to the dialog box dismiss ().
An example is provided:
12345678910111213141516171819 |
Private Popupwindow PW;
Private View view;
Private Linearlayout laymenu;
Layoutinflater Inflater = (layoutinflater) Main. getsystemservice (context. layout_inflater_service ); View = Inflater. Inflate (R. layout. popup_main_menu, Null ,
False ); Laymenu = (linearlayout) view. findviewbyid (R. Id. laymenu ); PW = New Popupwindow (view, layoutparams. wrap_content, layoutparams. wrap_content, True );
Laymenu. setonkeylistener ( New Onkeylistener ()
{
Public Boolean Onkey (view V, Int Keycode, keyevent event)
{
If (Event. getaction () = keyevent. action_down & keycode = Keyevent. keycode_back)
PW. Dismiss ();
Return False ;
} }); |
The code of the above two methods can coexist. Of course, if you use the first method, you do not need to capture the return key again, but you can try to capture other keys you need.