Thursday, December 15, 2011

[android-developers] Detecting key events from Dialog class?

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?

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

No comments:

Post a Comment