Obsługa działań na klawiaturze
Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
Wypróbuj tworzenie wiadomości
Jetpack Compose to zalecany zestaw narzędzi interfejsu na Androida. Dowiedz się, jak obsługiwać działania klawiatury w edytorze.
Gdy użytkownik nada fokus widokowi tekstu umożliwiającemu edycję, np. elementowi EditText
, a ma podłączoną klawiaturę sprzętową, system przejmuje wszystkie dane wejściowe. Jeśli jednak chcesz przechwycić lub bezpośrednio obsłużyć dane wejściowe z klawiatury, możesz to zrobić, implementując metody wywołania zwrotnego z interfejsu KeyEvent.Callback
, takie jak onKeyDown()
i onKeyMultiple()
.
Zarówno klasa Activity
, jak i View
implementują interfejs KeyEvent.Callback
, więc w odpowiednich przypadkach zazwyczaj zastępujesz metody wywołania zwrotnego w rozszerzeniu tych klas.
Uwaga: podczas obsługi zdarzeń klawiatury za pomocą klasy KeyEvent
i powiązanych interfejsów API należy pamiętać, że zdarzenia klawiatury pochodzą tylko z klawiatury sprzętowej. Nigdy nie polegaj na odbieraniu zdarzeń związanych z klawiszami w miękkiej metodzie wprowadzania danych (klawiatura ekranowa).
Obsługa zdarzeń pojedynczego klawisza
Aby obsłużyć naciśnięcie pojedynczego klawisza, w odpowiednim miejscu zastosuj funkcję onKeyDown()
lub onKeyUp()
. Zwykle używasz parametru onKeyUp()
, jeśli chcesz mieć pewność, że otrzymasz tylko 1 zdarzenie. Jeśli użytkownik naciśnie i przytrzyma klawisz, funkcja onKeyDown()
zostanie wywołana kilka razy.
Na przykład ta implementacja reaguje na niektóre klawisze klawiatury, aby sterować grą:
Kotlin
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_D -> {
moveShip(MOVE_LEFT)
true
}
KeyEvent.KEYCODE_F -> {
moveShip(MOVE_RIGHT)
true
}
KeyEvent.KEYCODE_J -> {
fireMachineGun()
true
}
KeyEvent.KEYCODE_K -> {
fireMissile()
true
}
else -> super.onKeyUp(keyCode, event)
}
}
Java
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_D:
moveShip(MOVE_LEFT);
return true;
case KeyEvent.KEYCODE_F:
moveShip(MOVE_RIGHT);
return true;
case KeyEvent.KEYCODE_J:
fireMachineGun();
return true;
case KeyEvent.KEYCODE_K:
fireMissile();
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
Obsługa klawiszy modyfikujących
Aby reagować na zdarzenia związane z klawiszami modyfikującymi, np. gdy klawisz jest używany w połączeniu z klawiszem Shift lub Control, możesz zapytać o KeyEvent
, który jest przekazywany do metody wywołania zwrotnego. Informacje o klawiszach modyfikujących, takich jak getModifiers()
i getMetaState()
, można uzyskać na kilka sposobów.
Najprostszym rozwiązaniem jest jednak sprawdzenie, czy naciśnięty jest klucz modyfikujący, który Cię interesuje, za pomocą metod takich jak isShiftPressed()
i isCtrlPressed()
.
Oto na przykład implementacja onKeyUp()
z dodatkowym przetwarzaniem, gdy klawisz Shift jest przytrzymany przy jednym z klawiszy:
Kotlin
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
...
KeyEvent.KEYCODE_J -> {
if (event.isShiftPressed) {
fireLaser()
} else {
fireMachineGun()
}
true
}
KeyEvent.KEYCODE_K -> {
if (event.isShiftPressed) {
fireSeekingMissle()
} else {
fireMissile()
}
true
}
else -> super.onKeyUp(keyCode, event)
}
}
Java
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
...
case KeyEvent.KEYCODE_J:
if (event.isShiftPressed()) {
fireLaser();
} else {
fireMachineGun();
}
return true;
case KeyEvent.KEYCODE_K:
if (event.isShiftPressed()) {
fireSeekingMissle();
} else {
fireMissile();
}
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
Dodatkowe materiały
Treść strony i umieszczone na niej fragmenty kodu podlegają licencjom opisanym w Licencji na treści. Java i OpenJDK są znakami towarowymi lub zastrzeżonymi znakami towarowymi należącymi do firmy Oracle lub jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2025-07-26 UTC.
[[["Łatwo zrozumieć","easyToUnderstand","thumb-up"],["Rozwiązało to mój problem","solvedMyProblem","thumb-up"],["Inne","otherUp","thumb-up"]],[["Brak potrzebnych mi informacji","missingTheInformationINeed","thumb-down"],["Zbyt skomplikowane / zbyt wiele czynności do wykonania","tooComplicatedTooManySteps","thumb-down"],["Nieaktualne treści","outOfDate","thumb-down"],["Problem z tłumaczeniem","translationIssue","thumb-down"],["Problem z przykładami/kodem","samplesCodeIssue","thumb-down"],["Inne","otherDown","thumb-down"]],["Ostatnia aktualizacja: 2025-07-26 UTC."],[],[],null,["# Handle keyboard actions\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to handle keyboard actions in Compose. \n[Handle keyboard actions in Compose →](/develop/ui/compose/touch-input/keyboard-input/commands#key_events) \n\nWhen the user gives focus to an editable text view, such as an\n[EditText](/reference/android/widget/EditText)\nelement, and the user has a hardware keyboard attached, all\ninput is handled by the system. However, if you want to intercept\nor directly handle the keyboard input yourself, you can do so by implementing callback methods\nfrom the [KeyEvent.Callback](/reference/android/view/KeyEvent.Callback)\ninterface, such as [onKeyDown()](/reference/android/view/KeyEvent.Callback#onKeyDown(int, android.view.KeyEvent))\nand [onKeyMultiple()](/reference/android/view/KeyEvent.Callback#onKeyMultiple(int, int, android.view.KeyEvent)).\n\nBoth the [Activity](/reference/android/app/Activity)\nand [View](/reference/android/view/View) classes implement the\n`KeyEvent.Callback` interface, so you\ngenerally override the callback methods in your extension of these classes, as\nappropriate.\n\n**Note:** When handling keyboard events with the\n[KeyEvent](/reference/android/view/KeyEvent) class and related APIs,\nexpect that the keyboard events are coming only from a hardware keyboard. Never rely on receiving key\nevents for any key on a soft input method (an on-screen keyboard).\n\nHandle single key events\n------------------------\n\nTo handle an individual key press, implement\n[onKeyDown()](/reference/android/app/Activity#onKeyDown(int, android.view.KeyEvent))\nor [onKeyUp()](/reference/android/app/Activity#onKeyUp(int, android.view.KeyEvent)),\nas appropriate. Usually, you use\n`onKeyUp()`\nif you want to ensure that you receive only one event. If the user presses and holds a key,\nthen `onKeyDown()` is called multiple times.\n\nFor example, this implementation responds to some keyboard keys to control a game: \n\n### Kotlin\n\n```kotlin\noverride fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {\n return when (keyCode) {\n KeyEvent.KEYCODE_D -\u003e {\n moveShip(MOVE_LEFT)\n true\n }\n KeyEvent.KEYCODE_F -\u003e {\n moveShip(MOVE_RIGHT)\n true\n }\n KeyEvent.KEYCODE_J -\u003e {\n fireMachineGun()\n true\n }\n KeyEvent.KEYCODE_K -\u003e {\n fireMissile()\n true\n }\n else -\u003e super.onKeyUp(keyCode, event)\n }\n}\n```\n\n### Java\n\n```java\n@Override\npublic boolean onKeyUp(int keyCode, KeyEvent event) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_D:\n moveShip(MOVE_LEFT);\n return true;\n case KeyEvent.KEYCODE_F:\n moveShip(MOVE_RIGHT);\n return true;\n case KeyEvent.KEYCODE_J:\n fireMachineGun();\n return true;\n case KeyEvent.KEYCODE_K:\n fireMissile();\n return true;\n default:\n return super.onKeyUp(keyCode, event);\n }\n}\n```\n\nHandle modifier keys\n--------------------\n\nTo respond to modifier key events, such as when a key is combined with \u003ckbd\u003eShift\u003c/kbd\u003e\nor \u003ckbd\u003eControl\u003c/kbd\u003e, you can\nquery the `KeyEvent`\nthat is passed to the callback method. Several methods\nprovide information about modifier keys, such as\n[getModifiers()](/reference/android/view/KeyEvent#getModifiers())\nand [getMetaState()](/reference/android/view/KeyEvent#getMetaState()).\nHowever, the simplest solution is to check whether\nthe exact modifier key you care about is being pressed with methods such as\n[isShiftPressed()](/reference/android/view/KeyEvent#isShiftPressed())\nand [isCtrlPressed()](/reference/android/view/KeyEvent#isCtrlPressed()).\n\nFor example, here's the `onKeyUp()` implementation\nagain, with extra handling for when the \u003ckbd\u003eShift\u003c/kbd\u003e key is held down with one of the keys: \n\n### Kotlin\n\n```kotlin\noverride fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {\n return when (keyCode) {\n ...\n KeyEvent.KEYCODE_J -\u003e {\n if (event.isShiftPressed) {\n fireLaser()\n } else {\n fireMachineGun()\n }\n true\n }\n KeyEvent.KEYCODE_K -\u003e {\n if (event.isShiftPressed) {\n fireSeekingMissle()\n } else {\n fireMissile()\n }\n true\n }\n else -\u003e super.onKeyUp(keyCode, event)\n }\n}\n```\n\n### Java\n\n```java\n@Override\npublic boolean onKeyUp(int keyCode, KeyEvent event) {\n switch (keyCode) {\n ...\n case KeyEvent.KEYCODE_J:\n if (event.isShiftPressed()) {\n fireLaser();\n } else {\n fireMachineGun();\n }\n return true;\n case KeyEvent.KEYCODE_K:\n if (event.isShiftPressed()) {\n fireSeekingMissle();\n } else {\n fireMissile();\n }\n return true;\n default:\n return super.onKeyUp(keyCode, event);\n }\n}\n```\n\nAdditional resources\n--------------------\n\n- [Keyboard Shortcuts Helper](/develop/ui/compose/touch-input/keyboard-input/keyboard-shortcuts-helper): System screen that enables users to search the keyboard shortcuts your app offers."]]