Which interface is used to detect key events from the Dialog class (Android SDK)?

淺唱寂寞╮ 提交于 2019-12-12 05:14:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!