Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

java - Android - Get keyboard key press

I want to catch the press of any key of the softkeyboard. I don't want a EditView or TextView in my Activity, the event must be handled from a extended View inside my Activity.

I just tried this:

1) Override the onKeyUp(int keyCode, KeyEvent event) Activity method. This don't work with softkeyboard, it just catch few hardkeyboard.

2) Create my OnKeyListener and register that in my View that contains a registered and working OnTouchListener. This doesn't work at all with softkeyboard.

3) Override the onKeyUp(int keyCode, KeyEvent event) View method. This not work at all neither if I set my OnKeyListener nor if I don't set it.

4) With the InputMethodManager object Call the method showSoftInput and passing it my View. This don't work neither for raise up the keyboard, indeed i have to call toggleSoftInput; nor to catch the key events.

I tested all only in the emulator but i think it's enough. Why it's so complicate take a simple key event from a keyboard ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For handling hardware keys and Back key you could use dispatchKeyEvent(KeyEvent event) in your Activity

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    Log.i("key pressed", String.valueOf(event.getKeyCode()));
    return super.dispatchKeyEvent(event);
}

UPD: unfortunately you can't handle soft keyboard events (see Handle single key events), unless you develop your own custom keyboard (follow the link to learn how Creating input method).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...