问题
I've created a simple custom dialog that asks users to "Press a key". The purpose of this is so that I can map whatever key they press to a function in the app. Unfortunately, I can not figure out what is the correct interface to use to detect the key events. My class looks like this:
public class ScancodeDialog extends Dialog implements OnKeyListener
{
public ScancodeDialog( Context context )
{
super(context);
setContentView( R.layout.scancode_dialog );
setTitle( "Key Listener" );
TextView text = (TextView) findViewById( R.id.scancode_text );
text.setText( "Please press a button.." );
ImageView image = (ImageView) findViewById( R.id.scancode_image );
image.setImageResource( R.drawable.icon );
getWindow().setFlags( WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM );
}
@Override
public boolean onKey( DialogInterface dialog, int keyCode, KeyEvent event )
{
if( keyCode != KeyEvent.KEYCODE_MENU )
dismiss();
return true;
}
}
I've tried it with and without the getWindow().setFlags() line (that was a suggestion from another question, which didn't help me in my case). Obviously I will add more functionality to the class later, but for now the dialog box should close whenever the user presses a key. However, onKey is never called.
I originally tried using the key listener interface from View:
import android.view.View.OnKeyListener;
But since a Dialog is not a view, this didn't work. I also tried the one from DialogInterface:
import android.content.DialogInterface.OnKeyListener;
This seemed like a better choice, since the API indicates that Dialog implements DialogInterface, but I am still not receiving the key events. Any suggestions I can try?
回答1:
You never declared the dialog to listen to the keys.
Example:
this.setOnKeyListener(...)
the this keyword is referring to the class that it is in.. which is a Dialog.
来源:https://stackoverflow.com/questions/8529653/which-interface-is-used-to-detect-key-events-from-the-dialog-class-android-sdk