Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start Activity when a key is hit

I want to start an activity when the user presses the space bar. My code is not detecting when the space bar is clicked.

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.KEYCODE_SPACE) {
        Toast.makeText(MainActivity.this, "YOU CLICKED SPACE KEY",
                Toast.LENGTH_LONG).show();
        return true;
    }
    Toast.makeText(MainActivity.this, "Didnt work", Toast.LENGTH_SHORT)
            .show();
    return super.dispatchKeyEvent(e);
};

}

like image 312
The Tokenizer Avatar asked Jul 01 '12 04:07

The Tokenizer


2 Answers

You can either set the listener to a View that has current focus, or use dispatchKeyEvent in your Activity, as seen in this answer.

Both will work.


Answer for your comments: If you've followed my link, you've probably implemented Activity.dispatchKeyEvent(KeyEvent) by now. :-)

The code doesnt register anykey i press, but when i push the back key it toasts for me "didnt work"

Do you happen to be using the emulator? I ask that because the latest SDK seems to have some problems with the emulator keyboard. The special keys (DPAD, HOME, BACK etc.) work, but the onscreen, QWERTY keyboard does not register any presses. The physical keyboard in my laptop won't register any presses either.

Don't ask me why.

And I say that because this week I posted the answer in the link, and it was working fine. The change is that I updated the Android SDK to R20/JB this morning, so I guess it could be a factor.

However, it will just work on a real device. I've just connected a physical keyboard to my tablet (P7510 / Honeycomb 3.2), and it listens to space presses just fine.

In case you're still doubting, here is proof: :-)

enter image description here

like image 181
davidcesarino Avatar answered Oct 21 '22 08:10

davidcesarino


public abstract boolean onKey (View v, int keyCode, KeyEvent event)

This function can be used to check that which key is pressed.

like image 40
Rishi Avatar answered Oct 21 '22 10:10

Rishi